我有一个支持OAuth2的Spring Boot应用程序。我有2个客户,每个客户都有自己的cliend 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
来获取该身份。
我应该在哪里添加该逻辑?
答案 0 :(得分: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);
这是使用版本2.0.9.RELEASE的spring-security-oauth。