Spring security 5:为 OAuth2 身份验证用户提供角色

Gre*_*zak 3 spring spring-security spring-security-oauth2

我有带有 Spring Security 5 和 OAuth2 客户端的现有 Spring Boot 应用程序,我已经成功配置了外部 OAuth2 提供程序(在我的例子中是 GitLab)的身份验证。

现在我在配置授权时遇到问题。我想要一些方法,让我编写代码来解析给定用户的角色(通​​过调用数据库或仅检查硬编码的用户名)。

我发现它可以通过使用PrincipalExtractorand来实现AuthoritiesExtractor,在一篇很好的文章中进行了描述。然而,这些类在最近的 Spring Security 中不再存在。与 Spring Security 5 兼容的替代方法是什么?

Tho*_*olf 5

你正在寻找的东西叫做GrantedAuthoritiesMapper

它记录官方 Spring Security 文档中

这是一个代码示例:

@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .oauth2Login(oauth2 -> oauth2
                .userInfoEndpoint(userInfo -> userInfo
                    .userAuthoritiesMapper(this.userAuthoritiesMapper())
                    ...
                )
            );
    }

    private GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                if (OidcUserAuthority.class.isInstance(authority)) {
                    OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;

                    OidcIdToken idToken = oidcUserAuthority.getIdToken();
                    OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();

                    // Map the claims found in idToken and/or userInfo
                    // to one or more GrantedAuthority's and add it to mappedAuthorities

                } else if (OAuth2UserAuthority.class.isInstance(authority)) {
                    OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;

                    Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();

                    // Map the attributes found in userAttributes
                    // to one or more GrantedAuthority's and add it to mappedAuthorities

                }
            });

            return mappedAuthorities;
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

spring security 文档中有更多示例和解释。