open source / oauth4s / jwt, jwk and jwks
JWT, JWK and JWKS
oauth4s-jwt works on its own, on java.security only. It is what a resource server needs to check the bearer
tokens it is sent.
scala
val keys: JwksSource[IO] = JwksSource.remote[IO](Endpoint("https://auth.example.com/jwks"))
val rules: JwtValidation =
JwtValidation
.of(issuer = "https://auth.example.com", audience = "https://api.example.com")
.withLeeway(30.seconds)
def verified(token: String): IO[Jwt] =
JwtVerifier.verify[IO](token, keys, rules) // fails with a JwtException; refetches the keys on an unknown key id
def offline(token: String, jwks: Jwks): Either[JwtError, Jwt] =
JwtVerifier.verify(token, jwks, rules, Instant.now()) // no effect, no networkscala
def read(jwt: Jwt): (Option[String], Vector[String], Option[Instant], Vector[String]) =
(jwt.claims.subject, jwt.claims.audience, jwt.claims.expiresAt, jwt.claims.raw.strings("roles"))
val stricter: JwtValidation =
rules
.withAlgorithms(JwsAlgorithm.ES256, JwsAlgorithm.RS256) // the default is every asymmetric algorithm
.withCheck(claims => Either.cond(claims.string("tenant").contains("acme"), (), JwtError.InvalidClaim("tenant", "another tenant's token")))| Family | Algorithms | Key |
|---|---|---|
| RSA PKCS#1 | RS256, RS384, RS512 |
JWK RSA |
| RSA PSS | PS256, PS384, PS512 |
JWK RSA |
| ECDSA | ES256, ES384, ES512 |
JWK EC on P-256, P-384, P-521 |
| HMAC | HS256, HS384, HS512 |
JWK oct; not accepted unless withAlgorithms names it |
The algorithm of a token has to be on the validation's list and has to fit the key: a token signed with a public key
used as an HMAC secret is refused, not verified. A key set with a key the library cannot use — an OKP key, a broken
one — still serves the rest.
Signing
scala
def signed(key: PrivateKey, now: Instant): Either[JwtError, String] =
val claims = Json.obj("iss" -> Json.str("billing"), "aud" -> Json.str("https://auth.example.com"), "exp" -> Json.num(now.getEpochSecond + 300))
JwtSigner.sign(claims, JwsAlgorithm.ES256, key, Some("key-1"))
def fromFile(pem: String): Either[JwtError, PrivateKey] =
JwtSigner.privateKey(pem, "EC") // a PKCS#8 "BEGIN PRIVATE KEY" file; "RSA" for an RSA key
built from README.md at v0.1.1
edit this page on GitHub