Spring OAuth2 限制用户通过客户端进行身份验证

Kar*_* B. 5 java security spring oauth-2.0

我正在实现一个 Spring OAuth2 应用程序,其中我有使用资源的不同客户端。

客户端是移动应用程序,所以我使用资源所有者密码流。

我的应用程序中有 2 个角色:普通用户和管理员。分别有2个客户端,一个是普通用户,一个是管理员。

我不想在移动应用程序(客户端)上应用逻辑来检查用户是否具有访问应用程序所需的角色。据我了解,令牌应该对客户端不透明。

我已经用用户角色限制了资源,但是当用户不应该使用该客户端时,我不希望身份验证服务器向客户端提供访问代码。

如何限制某些客户端上某些用户的授权?

提前致谢!

oauth 配置:

@SpringBootApplication
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().access("#oauth2.clientHasRole('ROLE_MANAGER') and hasRole('ROLE_MANAGER')");
    }

}

@Configuration
@EnableWebSecurity
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
            .and()
                .withUser("demo").password("password").roles("USER")
            .and()
                .withUser("manager").password("password").roles("MANAGER");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}


@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("manager-client")
                .authorizedGrantTypes("password", "refresh_token")
                .authorities("ROLE_MANAGER")
                .scopes("trust")
                .resourceIds(RESOURCE_ID);
    }
}
}
Run Code Online (Sandbox Code Playgroud)