Shikloshi
Shikloshi

Reputation: 3831

Secure REST Api with Spring boot and JWT

I'm trying to secure my REST server with JWT which I have implemented my self (Meaning that no spring stuff in the JWT handling it self, everything else is Spring of course).

I have this class: JWTToken implements Authentication.

I have a filter that is responsible of setting the JWTToken instance at the SecurityContextHolder:

public class JwtFilter extends GenericFilterBean {
public void doFilter(...) {
     ....
     JWTToken token = new JWTToken(jwt); // this init the Authentication object with all the jwt claims
     SecurityContextHolder.getContext().setAuthentication(token);
     ....
}

I also have a resource for debugging this:

@RequestMapping(
        value = "/protected_resource",
        method = RequestMethod.POST
)
@RolesAllowed("admin")
public RESTResponse<String> debugJwt() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // here I can see that the context is the right one
    return new RESTResponse<>("This was successful", "feedback message", true);
}

I am missing one peace of the puzzle which I could not found in any of the resources online and this is how to implement WebSecurityConfigurerAdapter and specifically the configure(HttpSecurity http) metohd.

When I tried do this, for instance:

http.authorizeRequests().anyRequest().authenticated()

Requests did not pass through this and the resource was not getting called.

What am I missing here?

Upvotes: 4

Views: 1802

Answers (1)

shayy
shayy

Reputation: 1312

Your JWTToken class should implement the method:

Collection<? extends GrantedAuthority> getAuthorities();

The implementation should return a collection of the user granted roles, one of them will be the "admin" role, something like:

public Collection<? extends GrantedAuthority> getAuthorities() {
    return Collections.singletonList(new SimpleGrantedAuthority("admin"));
}

Of course in your case you will query the DB or the JWT token and parse the user roles.

Upvotes: 3

Related Questions