I'm trying to find an example of how to get the groups a user belongs to in Okta in a Spring Boot application which uses Okta as its OIDC provider.
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 which gets username/
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.Map;
@RestController
public class UserController {
@GetMapping("/print-username")
public ResponseEntity<String> printUsername(@AuthenticationPrincipal OAuth2User principal) {
if (principal == null) {
return new ResponseEntity<>("User not authenticated", HttpStatus.UNAUTHORIZED);
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("User Attributes:\n");
// Print user attributes
Map<String, Object> attributes = principal.getAttributes();
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 (authorities)
Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();
for (GrantedAuthority authority : authorities) {
System.out.println("Authority: " + authority.getAuthority());
}
// Get the username from the email attribute (assuming email is the user identifier)
String username = (String) attributes.get("email");
System.out.println("Username: " + username);
return new ResponseEntity<>("Username printed in the server console", HttpStatus.OK);
}
}
Any thoughts on how to get the groups for a user from OKTA from a Spring Boot app?
You can create a groups claim in Okta by going to your admin console and navigating to Security > API. Select your authorization server and go to the Claims tab.
groups
ID Token
Groups
Matches regex
and use .*
as the valueThen, click Create.
Then, if you're using the Okta Spring Boot starter, your groups will automatically be converted to Spring Security authorities. If you want to use a name other than groups
, you can change that via properties.