<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-M74D8PB" height="0" width="0" style="display:none;visibility:hidden">
Loading
Skip to NavigationSkip to Main Content
0D54z00009VVqmkCADOkta Classic EngineAPI Access ManagementAnswered2023-08-24T19:43:00.000Z2023-08-02T23:20:35.000Z2023-08-03T21:32:26.000Z
Spring Boot / Okta - how to get user groups

Hello!

 

 

 

I'm trying to find some example of how to get the user group name and roles in a Spring Boot application. 

 

 

 

So far, I've gotten the user attributes and the Authority (which is alway "ROLE_USER"). But the part I'm missing is to how to get the list of groups the user belongs to? 

 

 

 

Here's the code so far:

 

 

 

@GetMapping("/print-username")

 

public ResponseEntity<?> printUsername(@AuthenticationPrincipal OAuth2User principal) {

 

  if (principal == null) {

 

    return new ResponseEntity<>("User not authenticated", HttpStatus.OK);

 

  } else {

 

 

 

    Map<String, Object> attributes = principal.getAttributes();

 

 

 

 

 

    // Print user attributes

 

 

 

    StringBuilder stringBuilder = new StringBuilder();

 

    stringBuilder.append("User Attributes:\n");

 

    for (Map.Entry<String, Object> entry : attributes.entrySet()) {

 

      stringBuilder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");

 

    }

 

 

 

    System.out.println(stringBuilder.toString());

 

 

 

 

 

    // Print user roles

 

    Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();

 

 

 

    for (GrantedAuthority authority : authorities) {

 

      System.out.println("Authority: " + authority.getAuthority());

 

    }

 

 

 

 

 

    String username = (String) attributes.get("email"); // Assuming email is the user identifier

 

    System.out.println("Username: " + username);

 

 

 

    return new ResponseEntity<>("Username printed in the server console", HttpStatus.OK);

 

  }

 

}

 

Any ideas? 

 

 

 

 


This question is closed.
Loading
Spring Boot / Okta - how to get user groups