上一篇文章我們講了通過在Spring Security 添加過濾器實現(xiàn)自定義登錄認(rèn)證,可以實現(xiàn)比如手機(jī)驗證碼登錄等其它方式登錄,但是有時候我們想更靈活一點(diǎn)。比如對于小程序我們已經(jīng)在微信認(rèn)證過了,只需要到Spring Security直接生成token就可以了。
針對這類需求,雖然通過上一篇文章自定義登錄方式也可以實現(xiàn),但是我們希望把這件事做的簡單點(diǎn),只有傻子才把簡單的事情復(fù)雜化。因此,我們在Spring Security實現(xiàn)了一個簡單粗暴的API,即直接通過API獲取JWT Tokn
上代碼
代碼很簡單
@RequestMapping(value = "token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> getUserToken(Principal principal, @RequestBody Map<String, String> parameters) {
// 調(diào)用端需要被提供client_credentials
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
}
// 保存請求參數(shù)
String clientId = this.getClientId(principal);
ClientDetails authenticatedClient = this.clientDetailsService.loadClientByClientId(clientId);
TokenRequest tokenRequest = this.oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
CustomAuthenticationToken authentication = customAuthenticationTokeService.createAuthenticationToken(clientId, parameters);
// 生成token
CustomTokenGranter tokenGranter = new CustomTokenGranter(
tokenServiceFactory.customJwtTokenService(), clientDetailsService, authentication);
OAuth2AccessToken token = tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest);
if (token == null) {
throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
} else {
return this.getResponse(token);
}
}
- 首先檢查principal是否存在,調(diào)用端需要提供client_credentials,否則不可以調(diào)用
- 生成
CustomAuthenticationToken,CustomAuthenticationToken為我們自定義的數(shù)據(jù)類,用于保存請求參數(shù) - 重點(diǎn)是通過
CustomTokenGranter生成token
CustomAuthenticationToken可以自行定義,只要能保存請求參數(shù)即可。本文我們沿用以前的CustomAuthenticationToken
public class CustomAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private String authType;
private Map<String,String[]> authParams;
private Object principal;
private Object credentials;
}
不過我們在createAuthenticationToken中會做一些參數(shù)檢查,如要求必須有principal和auth_type參數(shù)且要求auth_type=auth_finished"。如果有需要的話,還可以加一些自定義的內(nèi)容到CustomAuthenticationToken中。
@Service
public class CustomAuthenticationTokenServiceImpl implements CustomAuthenticationTokeService {
@Override
public CustomAuthenticationToken createAuthenticationToken(String clientId, Map<String, String> params) {
if (!params.containsKey("principal") || !params.containsKey("auth_type")) {
return null;
}
if (params.get("auth_type").equals("auth_finished")) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("user"));
Map<String, Object> detail = new HashMap<>(1);
detail.put("principal", params.get("principal"));
CustomAuthenticationToken token = new CustomAuthenticationToken(
params.get("auth_type"), params.get("username"), null, null, authorities);
token.setDetails(detail);
return token;
}
return null;
}
}
CustomTokenGranter用來生成token,最重要的不是grant方法,而是構(gòu)造函數(shù)我們傳遞的用于生成token的 AuthorizationServerTokenServices類
public class CustomTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "mini_app";
private boolean allowRefresh;
private Authentication authentication;
public CustomTokenGranter(
AuthorizationServerTokenServices tokenServices,
ClientDetailsService clientDetailsService,
Authentication authentication) {
super(tokenServices, clientDetailsService, new DefaultOAuth2RequestFactory(clientDetailsService), GRANT_TYPE);
this.authentication = authentication;
}
@Override
public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
OAuth2AccessToken token = super.grant(grantType, tokenRequest);
if (token != null) {
DefaultOAuth2AccessToken noRefresh = new DefaultOAuth2AccessToken(token);
if (!this.allowRefresh) {
noRefresh.setRefreshToken((null));
}
token = noRefresh;
}
return token;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
OAuth2Request storedOAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, authentication);
}
public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
public void setAllowRefresh(boolean allowRefresh) {
this.allowRefresh = allowRefresh;
}
}
AuthorizationServerTokenServices我們在上一篇文章有介紹過,不過在講一遍加深印象。
- 首先要配置 Token
- 定義你需要定義的內(nèi)容加入你的配置中
配置Token
token核心的生成邏輯defaultTokenService還是有Spring Security提供,但是我們其中加入了CustomTokenEnhancer用于在token內(nèi)容中加入我們需要的內(nèi)容,accessTokenConverter設(shè)置了我們token的密鑰和公鑰(密鑰生成參考:http://www.itdecent.cn/p/c9d5a2aa8648)
@Service
public class TokenServiceFactory {
private TokenKeyConfig tokenKeyConfig;
private ClientDetailsService clientDetailsService;
@Autowired
public TokenServiceFactory(
TokenKeyConfig tokenKeyConfig,
ClientDetailsService clientDetailsService) {
this.tokenKeyConfig = tokenKeyConfig;
this.clientDetailsService = clientDetailsService;
}
@Bean
public AuthorizationServerTokenServices customJwtTokenService() {
final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), accessTokenConverter()));
return defaultTokenService(tokenEnhancerChain);
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setAccessTokenConverter(new CustomAccessTokenConverter());
final KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
new ClassPathResource(tokenKeyConfig.getPath()), tokenKeyConfig.getPassword().toCharArray());
converter.setKeyPair(keyStoreKeyFactory.getKeyPair(tokenKeyConfig.getAlias()));
return converter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public org.springframework.security.oauth2.provider.token.TokenEnhancer tokenEnhancer() {
return new TokenEnhancer();
}
private AuthorizationServerTokenServices defaultTokenService(TokenEnhancerChain tokenEnhancerChain) {
final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);
defaultTokenServices.setClientDetailsService(clientDetailsService);
return defaultTokenServices;
}
}
加入自定義內(nèi)容
需要我們關(guān)心的內(nèi)容在于CustomTokenEnhancer, 因為我們需要在token中加入我們自定義的內(nèi)容,同時是加角色和用戶信息
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>();
Set<GrantedAuthority> rolesInfo = new HashSet<>();
Authentication userAuthentication = authentication.getUserAuthentication();
// client credential認(rèn)證,加入管理員角色
if (authentication.isClientOnly()) {
rolesInfo.add(new SimpleGrantedAuthority("admin"));
}
// 自定義認(rèn)證,增加detail
if (CustomAuthenticationToken.class.isAssignableFrom(userAuthentication.getClass())) {
rolesInfo.addAll(userAuthentication.getAuthorities());
additionalInfo.put("userInfo", userAuthentication.getDetails());
}
// 加入角色
additionalInfo.put("authorities", rolesInfo.stream().map(auth -> auth.getAuthority()).toArray());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
CustomAccessTokenConverter通常是把所有claims放到token 中
@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
OAuth2Authentication authentication = super.extractAuthentication(claims);
authentication.setDetails(claims);
return authentication;
}
}
看效果
-
首先獲取client_credential token
-
使用上述token作為header(不要忘記加bearer )獲取用戶的token
使用示例
我們有個后端服務(wù),想幫助小程序獲取token,在 Spring Cloud中那么它只要使用getUserToken方法即可獲取token
@FeignClient(name = "auth", configuration = AuthFeignConfigInterceptor.class)
@Service
public interface AuthClient {
/**
* get user token
* @param parameters parameters
* @return token
*/
@RequestMapping(method = RequestMethod.POST, value = "/oauth/api/external/token")
ResponseEntity<OAuth2AccessToken> getUserToken(@RequestBody Map<String, String> parameters);
}
AuthFeignConfigInterceptor用戶在getUserToken請求中加入client_credential的token
public class AuthFeignConfigInterceptor implements RequestInterceptor {
private static String TokenHeader = "authorization";
private static String AccessTokenPrefix = "bearer ";
private static Logger logger = LoggerFactory.getLogger(AuthFeignConfigInterceptor.class);
@Autowired
private ClientCredentialsResourceDetails clientCredentialsResourceDetails;
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header(TokenHeader, AccessTokenPrefix + getAccessTokenValue());
}
private String getAccessTokenValue() {
try {
logger.info("auth服務(wù)中獲取basic access token");
OAuth2AccessToken accessToken = this.getAccessTokenFromAuth();
return accessToken.getValue();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return this.getAccessTokenFromAuth().getValue();
}
}
private OAuth2AccessToken getAccessTokenFromAuth() {
ClientCredentialsAccessTokenProvider provider = new ClientCredentialsAccessTokenProvider();
return provider.obtainAccessToken(clientCredentialsResourceDetails, new DefaultAccessTokenRequest());
}
}
application.yml中需配置
security:
oauth2:
client:
clientId: app
clientSecret: testpassword
accessTokenUri: http://localhost:5000/oauth/oauth/token
grant-type: client_credentials
scope: all
面向Copy&Paste編程
- awesome-admin源碼
https://gitee.com/awesome-engineer/awesome-admin

