我正在使用Spring安全和Oauth 2.0认证协议来保护REST服务。
我已经实现了一个MVC Spring应用程序,它的工作很好。客户端通过提供客户端凭据(client_id &client_secret),用户凭证(username &(密码)调用定义在servlet-config.xml中的outh/token服务:
<http pattern="/oauth/token" create-session="stateless"
authentication-manager-ref="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security" >
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
如果凭据是有效的,客户端将得到一个访问令牌,如下所示:
{
"value": "b663f10d-553d-445b-afde-e9cd84066a1c",
"expiration": 1406598295994,
"tokenType": "bearer",
"refreshToken": {
"value": "36737abf-24bd-4b86-ad22-601f4d5cdee4",
"expiration": 1408890295994
},
"scope": [],
"additionalInformation": {},
"expiresIn": 299999,
"expired": false
}
我想有一个响应,也包含用户的详细信息,像这样:
{
"value": "b663f10d-553d-445b-afde-e9cd84066a1c",
"expiration": 1406598295994,
"tokenType": "bearer",
"refreshToken": {
"value": "36737abf-24bd-4b86-ad22-601f4d5cdee4",
"expiration": 1408890295994
},
"additionalInformation": {},
"expiresIn": 299999,
"expired": false,
"USER_ID": "1",
"USER_ROLE": "admin",
"OTHER DATA..."
}
有人知道实现这个的方法吗?
我一直在谷歌相当多,但我没有找到一个实现类似场景的例子。如果这个问题听起来很蠢,我很抱歉,但我是Spring Security的新手。
这就是我如何实现类似于您的场景。
1)创建自定义令牌增强器:public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>();
User user = (User) authentication.getPrincipal();
additionalInfo.put("user_id", user.getId());
additionalInfo.put("business_id", user.getBusinessId());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
2)用户自定义令牌增强器配置。
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancerChain())
.authenticationManager(authenticationManager)
.accessTokenConverter(jwtAccessTokenConverter());
}
/**
* Creates a chain of the list of token enhancers.
* @return
*
* @since 0.0.1
*
* @author Anil Bharadia
*/
public TokenEnhancerChain tokenEnhancerChain() {
TokenEnhancerChain chain = new TokenEnhancerChain();
chain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
return chain;
}
/**
* Get the new instance of the token enhancer.
* @return
*/
@Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
就是这样。下次请求令牌时,您将获得带有附加信息的令牌。
对于那些最近检查解决方案的人来说,这也是一个很好的解决方案。
@GetMapping("/token")
@ResponseBody
public String userinfo(@RegisteredOAuth2AuthorizedClient("${YOUR_CLIENT}") OAuth2AuthorizedClient authorizedClient) {
return authorizedClient.getAccessToken().getTokenValue();
}