jwtmicronautmicronaut-security

How do I load a "user" in a micronaut backend when JWT is provided


I have a Micronaut microservice that handles authentication via JsonWebTokens (JWT) from this guide.

Now I'd like to extend this code. The users in my app have some extra attributes such as email, adress, teamId etc. I have all users in the database.

How do I know in the backend controller method which user corresponds to the JWT that is sent by the client?

The guide contains this example code for the Micronaut REST controller:

@Secured(SecurityRule.IS_AUTHENTICATED)
@Controller
public class HomeController {
    @Produces(MediaType.TEXT_PLAIN)
    @Get
    public String index(Principal principal) {
        return principal.getName();
    }
}

I know that I can get the name of the principal, ie. the username from the HttpRequest. But how do I get my additional attributes?

(Maybe I misunderstand JWT a bit???)


edit Describing my usecase in more detail:

Security requirements of my use case

Authentication Flow

default oauth2 flow with JWTs:

Precondition: User is already registerd. Username, hash(password) and furhter attributes (email, adress, teamId, ..) are known on the backend.

  1. Client POSTs username and password to /login endpoint
  2. Client receives JWT in return, signed with server secret
  3. On every future request the client sends this JWT as bearer in the Http header.
  4. Backend validates JWT <==== this is what I want to know how to do this in Micronaut.

Questions


Solution

  • How do I load a “user” in a micronaut backend when JWT is provided?

    I am reading this as you plan to load some kind of User object your database and access it in the controller. If this is the case you need to hook into the place where Authentication instance is created to read the "sub" (username) of the token and then load it from the database.

    How to extend authentication attributes with more details ?

    By default for JWT authentication is created using JwtAuthenticationFactory and going more concrete default implementation is DefaultJwtAuthenticationFactory. If you plan to load more claims this could be done by replacing it and creating extended JWTClaimsSet or your own implementation of Authentication interface.

    How do I access jwt claims ?

    You need to check SecurityService -> getAuthentication() ->getAttributes(), it returns a map of security attributes which represent your token serialised as a map.

    How to validate that the JWT is valid?

    There is a basic validation rules checking the token is not expired and properly signed, all the rest validations especially for custom claims and validating agains a third parties sources have to be done on your own.

    If you plan to validate your custom claims, I have already open source a project in this scope, please have a look.

    https://github.com/traycho/micronaut-security-attributes

    How to extend existing token with extra claims during its issuing ?

    It is required to create your own claims generator extending JWTClaimsSetGenerator

    @Singleton
    @Replaces(JWTClaimsSetGenerator)
    class CustomJWTClaimsSetGenerator extends JWTClaimsSetGenerator {
    
        CustomJWTClaimsSetGenerator(TokenConfiguration tokenConfiguration, @Nullable JwtIdGenerator jwtIdGenerator, @Nullable ClaimsAudienceProvider claimsAudienceProvider) {
            super(tokenConfiguration, jwtIdGenerator, claimsAudienceProvider)
        }
    
        protected void populateWithUserDetails(JWTClaimsSet.Builder builder, UserDetails userDetails) {
            super.populateWithUserDetails(builder, userDetails)
    
            // You your custom claims here
            builder.claim('email', userDetails.getAttributes().get("email"));
    
        }
    }