<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
Okta Support Agent (Beta)

Terms of Service

Hello! I'm the Okta Support Agent (Beta), your go-to resource for questions about Okta products. Please remember for your security and privacy, do not share any Personally Identifiable Information (PII) such as passwords, IP addresses, or other details with me.

Okta Privacy Policy and Terms of Service apply