spring Cloud微服务 security+oauth2认证授权中心自定义令牌增强,并实现登录和退出_spring security实现微服务用户中心
在Spring Cloud微服务架构中,使用Spring Security和OAuth2构建认证授权中心,并实现自定义令牌增强和登录退出的示例代码如下:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private DataSource dataSource;
@Autowired
private TokenStore tokenStore;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
private CustomTokenEnhancer customTokenEnhancer;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancer = new TokenEnhancerChain();
tokenEnhancer.setTokenEnhancers(Arrays.asList(customTokenEnhancer, jwtAccessTokenConverter));
endpoints
.tokenStore(tokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.tokenEnhancer(tokenEnhancer)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("isAnonymous() || hasAuthority('SCOPE_read')")
.checkTokenAccess("hasAuthority('SCOPE_read')");
}
}
@Component
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.getUsername());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
@RestController
public class L
评论已关闭