in

Convert JWT Authentication Principal to something more usable in spring


I’m struggling to find an answer to this on the interwebs.

I have a spring boot microservice that validates a JWT (issued by a different service) for authentication. It is working nicely, and I can access the JWT details in my controller like so:

// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'

// MyController.java
@RestController
@RequestMapping("/")
public class MyController {
    @GetMapping()
    public String someControllerMethod(@AuthenticationPrincipal Jwt jwt) {
        int userId = Integer.parseInt(jwt.getClaim("userid"));
        ...
    }
}

That works great. I can extract what I need from the JWT and go on to talk to my database with the correct userid etc.

However I find it a bit tedious to have to use the Jwt type to get these values in each controller. Is there a way I can inject a different type as the @AuthenticationPrincipal?

E.g. my own class which has already extracted what is needed from the JWT, and exposes something like .getUserId() that returns an int?
That would also let me centralise the logic of parsing the claims or throwing exceptions if they are not as expected etc.



Source: https://stackoverflow.com/questions/70626334/convert-jwt-authentication-principal-to-something-more-usable-in-spring

Studio 54 NFT’s — Shopify for NFT’s

Calculator App Solution Built With Vue