MrrrLuiigii
MrrrLuiigii

Reputation: 41

How to access java.security.Principal attributes inside Spring Boot controller?

I have an Angular frontend which prompts the user to login using Microsoft Azure Active Directory. The correct headers are added to the request when the user accesses my API.

My API is a Spring Boot Rest API secured according to this (Protect a resource server/API) guide.

My controller has the following method using the java.security.Principal interface as a parameter.

@GetMapping("/test")
ResponseEntity<Object> test(Principal principal) {
    return ResponseEntity.ok(principal);
}

When I set a breakpoint I see the attributes I want to get like principal.attributes.unique_name, but I am not able to access those attributes through the Principal interface. Any idea on how to achieve this?

PS: I've had a look at similar questions like this one (How to get all attributes from java.security.Principal?), but their answers were not able to help me...

Upvotes: 0

Views: 3594

Answers (1)

MrrrLuiigii
MrrrLuiigii

Reputation: 41

As stated in this Baeldung guide you can get access to the principal via the SecurityContextHolder.

Casting this object to AADOAuth2AuthenticatedPrincipal provides access to the principle properties as follows.

AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Map<String, Object> attributes = principal.getAttributes();
String name = String.valueOf(attributes.get("unique_name"));

Another option is to use the AADOAuth2AuthenticatedPrincipal directly in the controller parameters by using the @AuthenticationPrincipal annotation as pointed out in the comments below.

@GetMapping("/test")
    ResponseEntity<String> test(@AuthenticationPrincipal AADOAuth2AuthenticatedPrincipal principal) {
        Map<String, Object> attributes = principal.getAttributes();
        String name = String.valueOf(attributes.get("unique_name"));
        return ResponseEntity.ok(name);
    }

Upvotes: 1

Related Questions