Home > OS >  How to return the list of Roles that the user has?
How to return the list of Roles that the user has?

Time:05-26

I followed the article, https://docs.microsoft.com/en-us/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory and created an App role

The below endpoint uses users role to authorize

@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api")
public class TutorialController {

    @Autowired
    TutorialRepository tutorialRepository;

     @PreAuthorize("hasAnyAuthority('APPROLE_Admin', 'APPROLE_Contributor')")
    @GetMapping("/tutorials")
    public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
        try {
            List<Tutorial> tutorials = new ArrayList<Tutorial>();

I want to introduce an additional Get Endpoint to return the list of Roles that the user has?

Update: 25/05/2022

I have added an additional mapping as mentioned below

@GetMapping("/roles")
public ResponseEntity<List<GrantedAuthority>> getRoles() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    List<GrantedAuthority> authorities = (List<GrantedAuthority>) userDetails.getAuthorities();
    return (ResponseEntity<List<GrantedAuthority>>) authorities;
}

Getting the error:

java.lang.ClassCastException: class org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser cannot be cast to class org.springframework.security.core.userdetails.UserDetails

CodePudding user response:

If you have set your security configuration up properly, you can get the current users' roles as below.

SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
List<GrantedAuthority> authorities = userDetails.getAuthorities();

CodePudding user response:

The GrantedAuthorities are available on the Authentication class, so once you have this you can call getAuthorities() directly and get back a Collection of GrantedAuthorty.

@GetMapping("/roles")
public ResponseEntity<List<GrantedAuthority>> getRoles() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return ResponseEntity.of(authentication.getAuthorities());
}
  • Related