Spring Boot 3 Security with JWT Verification without Users

769 views Asked by At

I have a Microservice with an rest endpoint to receive data.

I will secure this endpoint not with a user/Password rather with an JWT Token. The secret from this token is known to this service.

I take a look into the spring security and see that all providers need a representation from a user service or user object, also the custom implementation.

It is not possible to verify a token get back an true/false and the Security Configuration know that this request is allowed or the caller get back a 401.

I have no identity provider behind and no database with users or something else.

Of course, I can create a request filter, check the auth header, verify the token, and send back in case auf false an http status 401. In my opinion this is not a good solution.

Can I use spring security or is this not possible, because that I have no users or login logic.

If it is possible, how do I do it correctly?

Thanks

1

There are 1 answers

2
Toerktumlare On

If you only wish to verify the signage of the token, and check that claims are valid or not and construct a principal from the data in the token, you are looking for something called the resource server implementation and is part of the oauth2 rfc.

After someone has authenticated correctly, and are given i session in a cookie to the browser. When this cookie is provided to the backend, one pattern is for a proxy to verify this cookie and exchange it for a JWT token that is used internally inside a private network to perform authorize requests between micro services.

JWT Tokens where never designed to be handed out to browsers since they lack the security features that for instance cookies possess, for instance httpOnly Secure and same site.

There is no current way to securely store a JWT in a browser as of time of writing this.

So to answer your question, if you are doing service to service authorization, use the resource server functionality it is well documented here oauth2 resource server for both opague and jwt tokens. Here is a working code example.

If you are doing Browser to backend communication, then you should not be using JWTs at all, you should either be using a private oauth2 client that is using the authorization code flow that will hand out cookies to the browser. Or you should implement the BFF pattern

Or if you just want a simple username password login i recommend implementing FormLogin

Please only use JWTs for their intended purpose, authorization between micro services.