春季 OAuth2 检查用户范围未按预期工作

首先,根据Spring doc,如果我想将用户角色映射到范围,我应该使用setCheckUserScopes(true)到DefaultOAuth2RequestFactory。因此,一种方法是注入我自己的DefaultOAuth2RequestFactory bean,如doc所说:

The AuthorizationServerEndpointsConfigurer allows you to inject a custom OAuth2RequestFactory so you can use that feature to set up a factory if you use @EnableAuthorizationServer.

然后我做

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends
        AuthorizationServerConfigurerAdapter {

    ...

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .tokenStore(tokenStore)
                .tokenServices(tokenServices());

       endpoints
            .getOAuth2RequestFactory(); // this doesn't return me my own DefaultOAuth2RequestFactory 

    }

    @Bean
    @Primary
    public OAuth2RequestFactory defaultOAuth2RequestFactory() {
        DefaultOAuth2RequestFactory defaultOAuth2RequestFactory = new DefaultOAuth2RequestFactory(
                clientDetailsService);
        defaultOAuth2RequestFactory.setCheckUserScopes(true);
        return defaultOAuth2RequestFactory;
    }
}

编辑

我忽略了AuthalitionServerEndpointsConfigurer中的方法requestFactory()。这是将其传递给Spring Security的正确方法。将 OAuth2RequestFactory Bean 设置为主节点不起作用。我删除了一些东西来关注真正的问题:


经过这个观察,实际问题:

据我所知,如果用户具有权限A和B,并且应用程序具有范围A,那么他只获得“A”范围。但这并没有发生。真正发生的事情是,如果应用程序具有范围A,并且APP(不是用户)具有权限A和B,则用户获得A。但这没有任何意义。这是解析用户作用域的 DefaultOAuth2RequestFactory 方法:

private Set<String> extractScopes(Map<String, String> requestParameters, String clientId) {
    ... // I avoid some unimportant lines to not make this post so long
    if ((scopes == null || scopes.isEmpty())) {
        scopes = clientDetails.getScope();
    }

    if (checkUserScopes) {
        scopes = checkUserScopes(scopes, clientDetails);
    }
    return scopes;
}

private Set<String> checkUserScopes(Set<String> scopes, ClientDetails clientDetails) {
    if (!securityContextAccessor.isUser()) {
        return scopes;
    }
    Set<String> result = new LinkedHashSet<String>();
    Set<String> authorities = AuthorityUtils.authorityListToSet(securityContextAccessor.getAuthorities());
    for (String scope : scopes) {
        if (authorities.contains(scope) || authorities.contains(scope.toUpperCase())
                || authorities.contains("ROLE_" + scope.toUpperCase())) {
            result.add(scope);
        }
    }
    return result;
} 

这是一个错误吗?如果我错了,请告诉我。问候


答案 1

您需要通过类似此处的代码连接OAuth2RequestFactory。

如果权限是由 ClientDetailsService 设置的,那么你应该是好的。如果你想映射登录的用户权限,我也没有运气


答案 2

推荐