set kid when signing with a key, allow setting the value

This commit is contained in:
Guillaume Buisson 2020-01-31 13:25:37 +01:00
parent 9086f25609
commit 60cfa068c1
No known key found for this signature in database
GPG key ID: B7C4D34768824B2C
2 changed files with 69 additions and 60 deletions

View file

@ -8,6 +8,8 @@
[clojure.string :as str]))
(def ^:private DEFAULT_SIGNATURE_ALGORITHM :HS256)
(def ^:private DEFAULT_KID nil)
(def ^:private map->encoded-json (comp url-safe-encode-str
#(json/write-str % :key-fn write-key)))
(def ^:private encoded-json->map (comp #(json/read-str % :key-fn read-key)
@ -48,18 +50,22 @@
(defprotocol JsonWebSignature
"Protocol for JonWebSignature"
(set-alg [this alg] "Set algorithm name to JWS Header Parameter")
(sign [this key] [this alg key] "Set signature to this token")
(set-kid [this kid] "Set Key ID to JWS Header Parameter")
(sign [this key] [this alg key] [this alg key kid] "Set signature to this token")
(verify [this] [this key] [this algorithm key] "Verify this token"))
(extend-protocol JsonWebSignature
JWT
(set-alg [this alg]
(assoc-in this [:header :alg] (name alg)))
(set-kid [this kid]
(assoc-in this [:header :kid] kid))
(sign
([this key] (sign this DEFAULT_SIGNATURE_ALGORITHM key))
([this alg key]
(let [this* (set-alg this alg)
([this key] (sign this DEFAULT_SIGNATURE_ALGORITHM key DEFAULT_KID))
([this alg key] (sign this alg key DEFAULT_KID))
([this alg key kid]
(let [this* (cond-> (set-alg this alg)
(some? kid) (set-kid kid))
sign-fn (get-signature-fn alg)
data (str (encoded-header this*) "." (encoded-claims this*))]
(assoc this* :signature (sign-fn key data) :encoded-data data))))

View file

@ -60,6 +60,9 @@
"GDINiGX-htlD1-33F4VXK8lUXbdm1n9F1fpHcOFksScniWMvC5f9520jdxyb5c-9CmXz21iDtFdFKWGG"
"zlT_hPjZ0Ta_M8goReBO0L-nDM5hJHxzEqgSZQ7tkcJ18PCdxeMia5NMRV0shGMMUzU")
(-> claim jwt (sign :RS256 rsa-prv-key "foo") to-str)
=> "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImZvbyJ9.eyJpc3MiOiJmb28ifQ.hYL0352XhNo0z5u6queNjnVBeKxFXwyB1ELLk1G009eTQN5srC2dDdG9k66Free0vNpreCTGq1im4cQUvBUi12Fsyls1p7VBVnIABuc6ZUjyyLD7fDtXF_MqGksPrCcffQlW4Qj2WA_CkRU9qJCwvU-H5c1HIn6QX29hdeu1kzY"
(-> claim jwt (sign :RS256 rsa-enc-prv-key) to-str)
=> (str "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmb28ifQ.E20DLUOR5VeoTKtH5FjR71rm"
"_rZV2AdXYDQCxqHpMWyZSO6wO4g67phTD727izDxd_NjuNXd2m7Atth7tGABaMhqHLh9EUwba_0nTbw6"