clojure - 如何使用 java-time 生成 JWT exp 声明?

标签 clojure jwt java-time date-parsing

JWT token 的大多数示例都使用 clj-time,现已弃用,转而使用 native java.time。我正在尝试使用 java-timebuddy 来签名/验证 token ,但我一直试图将 exp 声明传递给我的 token 。这是我所拥有的示例:

(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}))

当我尝试测试是否可以取消对 token 的签名时

(jwt/unsign token secret {:alg :hs512})

我收到以下错误:

Execution error (JsonGenerationException) at cheshire.generate/generate (generate.clj:152). Cannot JSON encode object of class: class java.time.LocalDateTime: 2021-01-22T12:37:52.206456

因此,我尝试通过将对 (t/plus ...) 的调用封装在 (str) 内来传递相同的内容,但随后出现此错误:

class java.lang.String cannot be cast to class java.lang.Number
(java.lang.String and java.lang.Number are in module java.base of loader 'bootstrap')

所以,我陷入了困境,因为我真的不知道如何使用 java-time 生成有效的 exp 数值(根据 this 问题,格式应该是自纪元以来的秒数)。 Older examples using 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))

最佳答案

这里有两种方法:

  (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+60            => <#java.time.Instant #object[java.time.Instant 0x7ce0054c "2021-01-22T19:04:51.905586442Z"]>
now+60-unixsecs   => <#java.lang.Long 1611342291>

所以你可以选择不同的方法。看来 buddy 知道如何从 java.time.Instant 进行转换,因此无需一直转换为 unix-seconds。

您可能也对此感兴趣library of helper and convenience functions用于使用java.time

关于clojure - 如何使用 java-time 生成 JWT exp 声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65851030/

相关文章:

spring-boot - 如何在通过keycloak生成的访问 token (JWT)中添加自定义字段?

java - 一年中最后一天的时间转换错误

java - java.time API 如何确定政府对区域规则的更改?

java - 使用新的 java.time API 解析时区非常慢

clojure.tools.logging EvalReader 使用?

clojure - 用于匹配尾部斜杠的 Compojure 正则表达式

.net - 使用客户端凭据的 Azure AD .NET 6 中的 token 无效

ios - JWT 用于从服务器发送 iOS 推送消息

clojure - 如何将 korma 选择结果转换为 json 以提供休息服务(compojure)?

clojure - 更具可读性的 Compojure 路线