Spring Boot / Okta - 如何检索用户组

问题描述 投票:0回答:0

我正在尝试找到一个示例,说明如何在使用 Okta 作为其 OIDC 提供程序的 Spring Boot 应用程序中获取用户在 Okta 中所属的组。

到目前为止,我已经获得了用户属性和权限(始终为“ROLE_USER”)。

但是我缺少的部分是如何获取用户所属组的列表。

这是获取用户名的代码/

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);
    }
}

关于如何从 Spring Boot 应用程序从 OKTA 获取用户组有什么想法吗?

admin roles okta group okta-api
© www.soinside.com 2019 - 2024. All rights reserved.