1

I'm sending the request with jwt token in Authorization. I need to fetch it somehow and I tried by this way:

@GetMapping
fun getUser(@AuthenticationPrincipal jwt: Jwt<*, *>): ResponseEntity<UserDto?> {
   val allClaimsFromToken: Claims? = getAllClaimsFromToken(jwt.toString());
   val userNameFromJwtToken: Any? = allClaimsFromToken?.get("sub");
   ....
}

Unfortunately I get all the time null as jwt variable. Could you tell me what am I doing wrong?

ced-b
  • 3,957
  • 1
  • 27
  • 39
papakakaka
  • 13
  • 4

1 Answers1

0

Probably the most straight forward way of doing this would be to get the raw header value and then parse it with JJWT.

@GetMapping
fun getUser(@RequestHeader (name="Authorization") tokenEncoded: String): ResponseEntity<UserDto?> {
   Jwt myToken = Jwts.parserBuilder()    
     .setSigningKey(yourKeyHere)
     .build()
     .parseClaimsJws(tokenEncoded.removePrefix("Bearer").trim());

   // do something
}

You could also look into using the Spring library for OAuth2 it automates a bit more. Or you can create a filter that does the parsing so you don't have to repeat this on every web call.

Also see this post for further ideas Accessing JWT Token from a Spring Boot Rest Controller . It's Java, but basically the same applies.

ced-b
  • 3,957
  • 1
  • 27
  • 39