Nick H
Nick H

Reputation: 8992

How to generate a JWT/JWS with JWE

I am developing a j2ee authentication/authorization system. I want to use JWT tokens, sign the payload with JWS and encrypt it using JWE.

I found a decent tutorial from bitbuckets jose4j

This example shows them generating a JWK using EllipticCurveJsonWebKey. I don't understand how this could be used for authentication/authorization. Wouldn't you need to store a secret key in a properties file or JNDI entry then use that key to sign/encrypt the JWT? This way when I receive an http request I can use that same key to verify the JWT. Most of the tutorials I have found use a similar example.

How could this be done with the same server side secret key?

Upvotes: 1

Views: 5175

Answers (1)

ingenious
ingenious

Reputation: 966

First things first - go checkout this article about authentication with OAuth2.0. Depending on your background you might need to do some reading into OAuth & OpenID Connect themselves.

However if you just want to keep your server side session in a signed and encrypted JWT, that's also OK. In your JWT you will need a couple of claims, at the very least some indicating:

  • when was the session created (iat)
  • how long is the session still valid (exp)
  • who created the session, that's your auth system (iss)
  • who is authenticated by this session, that's your user id or something (sub)

Later you can add an audience and preferably a nonce. However if you're encrypting everything you might also get on with it without a nonce.

It is generally a good idea to refer to the suggested claims in the OIDC core spec.

And here is where it gets tricky. You've basically got two options - you can either generate server side a string, which is completely opaque to all applications and becomes the session. Then offer a token introspection endpoint, where clients can send this string to and retrieve the claims described above (plus all additional ones you decide to map to your session). This also means that you will need some storage where these opaque strings are persisted along with the user claims they map to.

Alternatively you can just sign (and optionally encrypt) the whole bunch and send it over the wire. You'll have to just an ID for the token, only if you need to be able to logout users. Signing the token is done with a private key, which only your application knows about and verification in any client is done by a public key, which your application can share e.g. by offering a JWKs endpoint.

Depending on the claims you put in your JWT you might not really need to encrypt it at all... If you do however, then yes, you'll have to manage the keys for encryption as well.

Also check this article for a very good overview on what is what in token auth.

Upvotes: 1

Related Questions