JWT令牌的大多数示例都使用clj时间,现在不再推荐使用本机java.time。我试图使用爪哇时间和巴迪对令牌进行签名/验证,但我只能尝试将exp声明传递给令牌。下面是我所拥有的一个例子:
(ns test-app.test-ns
(:require
[buddy.sign.jwt :as jwt]
[buddy.auth.backends.token :as bat]
[java-time :as t]))
(def secret "myfishysecret")
(def auth-backend (bat/jws-backend {:secret secret
:options {:alg :hs512}}))
(def token (jwt/sign {:user "slacker"
:exp (t/plus (t/local-date-time) (t/seconds 60))
} secret {:alg :hs512}))当尝试测试是否可以解除标记时
(jwt/unsign token secret {:alg :hs512})我得到以下错误:
执行错误(JsonGenerationException)在cheshire.generate/generate (generate.clj:152)。JSON无法编码类对象:类java.time.LocalDateTime: 2021-01-22T12:37:52.206456
因此,我试图通过封装对(t/plus .)的调用来传递相同的结果。在一个(str)内部,然后我得到这个错误:
不能将类java.lang.String转换为类java.lang.Number (java.lang.String和java.lang.Number在加载程序‘bootstrap’的模块java.base中)
因此,由于我不知道如何使用java-time生成有效的exp值(根据这问题,格式应该以秒为单位),所以我被困住了。使用clj-time的旧示例刚刚将exp索赔值传递为
(clj-time.core/plus (clj-time.core/now) (clj-time.core/seconds 3600))任何帮助都是非常感谢的。
编辑:艾伦·汤普森的答案工作得很好,因为使用java-time包装器,这是等价的:
(t/plus (t/instant) (t/seconds 60))发布于 2021-01-22 19:05:16
以下是两种方法:
(let [now+60 (-> (Instant/now)
(.plusSeconds 60))
now+60-unixsecs (.getEpochSecond now+60)]
(jwt/sign {:user "slacker" :exp now+60 } secret {:alg :hs512})
(jwt/sign {:user "slacker" :exp now+60-unixsecs} secret {:alg :hs512}))我们有now的结果:
now+60 => <#java.time.Instant #object[java.time.Instant 0x7ce0054c "2021-01-22T19:04:51.905586442Z"]>
now+60-unixsecs => <#java.lang.Long 1611342291>所以你可以选择你的方法。看来巴迪知道如何从java.time.Instant进行转换,所以一直使用unix-秒是不必要的。
您也可能对这个使用助手和方便函数库的java.time感兴趣。
https://stackoverflow.com/questions/65851030
复制相似问题