Developer
Developer

Reputation: 533

Getting subject from id token in Spring boot

I have configured my Spring Boot application as a resource server. And it is working perfectly by blocking all the request that does not contain the authentication bearer token. However, once I am in service I would like to get the subject(sub in JWT token) out of the token an use it. How can I fetch the value of subject from Spring Authentication framework?

Since I am using Spring Boot's auto-configuration, I do not validate the token myself, it is been done automaticlly so I do not know the subject.

Upvotes: 1

Views: 3198

Answers (2)

Developer
Developer

Reputation: 533

I added Principle to the argument.

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

This link helped me

Upvotes: 0

RBH
RBH

Reputation: 271

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;    
...
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
...

Upvotes: 2

Related Questions