1

我有一个支持 OAuth2 的 Spring Boot 应用程序。我有 2 个客户,每个客户都有自己的客户 ID:

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static final String RESOURCE_ID = "my-rest-service";

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
               .withClient("clientOne")
               .authorizedGrantTypes("password", "refresh_token")
               .authorities("USER")
               .scopes("read", "write")
               .resourceIds(RESOURCE_ID)
               .secret("123456"))
               .and()
               .withClient("clientTwo")
               .authorizedGrantTypes("password", "refresh_token")
               .scopes("read","write")
               .resourceIds(RESOURCE_ID)
               .secret("789654")
               ;

    }
}

此外,我有一个User其中有一个Role. 我现在希望具有角色 ROLE_ONE 的用户在使用时只能获取身份验证令牌,clientOne而具有 ROLE_TWO 的用户只能使用clientTwo来获取该令牌。

我应该在哪里添加该逻辑?

4

1 回答 1

0

我现在所做的(但我很想听听是否有其他/更好的选择)是创建一个ResourceOwnerPasswordTokenGranter从方法复制代码getOAuth2Authentication并添加我的自定义逻辑的子类:

...
if (userAuth == null || !userAuth.isAuthenticated()) {
    throw new InvalidGrantException("Could not authenticate user: " + username);
}

// Start of custom code
if( client.getClientId().equals("gamePlayClient")) {
  if( !((CustomUserDetails)userAuth.getPrincipal()).hasPlayerRole()) {
    throw new InsufficientAuthenticationException("Only users with the role 'PLAYER' can log on this client.");
  }
}
// End of custom code

OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);

这是使用 spring-security-oauth 的 2.0.9.RELEASE 版本。

于 2016-06-22T12:39:12.653 回答