So here is the scenario.
I have login API and it return jwt token to client, this API has annotation @PermitAll.
Then I have another API that is secured and can only be accessed after verifying jwt token. The request to secured API is sent in such a manner that Authorization parameter is added in the header with the value of jwt token and the request is passed to the secured API. Please note that authorization type for this API is No Auth. I wrote a class JwtRequestFilter extends OncePerRequestFilterin which i intercepted the request, extracted the token, verified it, returned appropriate response, it all works well. But there is a problem, and the problem is that there is @PreAuthorize("hasAuthority('RANDOM_PRIV_1')") annotation at the top of the method in the controller class and it is not verified by the JwtRequestFilter and practically it shouldn't be since this is not its job to do that.
I know list of GrantedAuthorities are passed to the implementation of UserDetailsService and it gets verified by method loadUserByUsername. But I cannot use this interface's implementation, reason being, its implementation is called only when authorization type is Basic Auth and I am not using this type of Authentication.
So what I am looking for is an interface/class with I can verify GrantedAuthorities; the way it is verified by UserDetailsService.
If there is not such functionality then I have second working option of extending HandlerInterceptorAdapter and in the preHandle, I verify token as well as verify grantedAuthorities associated with user and verify(manually) them against the PreAuthorize annotation present on the method. This is working for me, but still I am looking for much cleaner solution.
P.S: I went through this link as well but didn't find any useful information. Spring boot basic authentication without UserDetailsService method.
Any help would be really appreciated.
If you are wanting to use JWTs to authenticate requests, then you can use Spring Security's built-in support for it.
You'll still need to create the JWT yourself, but for processing the JWT and turning it into Granted Authorities, you can do:
This tells Spring Security to stand up a filter (
BearerTokenAuthenticationFilter) that extracts the token and processes it, probably a lot like yourJwtRequestFilter.Since you are creating the JWT locally (instead of using an Authorization Server, for example), you'll need to tell Spring Security how to verify the token. This is usually done with a symmetric key:
And finally, to your question about granted authorities. Assuming, for example, that the authority you mentioned (
RANDOM_PRIV_1) is listed as a scope in your JWT, you can construct aJwtAuthenticationConverterbean:And then add that to the DSL:
Then, when a JWT is presented in the request, Spring Security will process it, extract authorities, and verify that they match the one using the
@PreAuthorizeannotation.