欢迎访问Spring Cloud中国社区

《重新定义Spring Cloud实战》由Spring Cloud中国社区倾力打造,基于Spring Cloud的Finchley.RELEASE版本,本书内容宽度足够广、深度足够深,而且立足于生产实践,直接从生产实践出发,包含大量生产实践的配置。欢迎加微信Software_King进群答疑,国内谁在使用Spring Cloud?欢迎登记

Spring Security OAuth 个性化token

冷冷 · 1月前 · 186 ·

个性化Token 目的

  • 默认通过调用 /oauth/token 返回的报文格式包含以下参数
  1. {
  2. "access_token": "e6669cdf-b6cd-43fe-af5c-f91a65041382",
  3. "token_type": "bearer",
  4. "refresh_token": "da91294d-446c-4a89-bdcf-88aee15a75e8",
  5. "expires_in": 43199,
  6. "scope": "server"
  7. }

并没包含用户的业务信息比如用户信息、租户信息等。

  • 扩展生成包含业务信息(如下),避免系统多次调用,直接可以通过认证接口获取到用户信息等,大大提高系统性能
  1. {
  2. "access_token":"a6f3b6d6-93e6-4eb8-a97d-3ae72240a7b0",
  3. "token_type":"bearer",
  4. "refresh_token":"710ab162-a482-41cd-8bad-26456af38e4f",
  5. "expires_in":42396,
  6. "scope":"server",
  7. "tenant_id":1,
  8. "license":"made by pigx",
  9. "dept_id":1,
  10. "user_id":1,
  11. "username":"admin"
  12. }

密码模式生成Token 源码解析

image

​ 主页参考红框部分

  • ResourceOwnerPasswordTokenGranter (密码模式)根据用户的请求信息,进行认证得到当前用户上下文信息

    1. protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    2. Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
    3. String username = parameters.get("username");
    4. String password = parameters.get("password");
    5. // Protect from downstream leaks of password
    6. parameters.remove("password");
    7. Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    8. ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    9. userAuth = authenticationManager.authenticate(userAuth);
    10. OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
    11. return new OAuth2Authentication(storedOAuth2Request, userAuth);
    12. }
  • 然后调用AbstractTokenGranter.getAccessToken() 获取OAuth2AccessToken

    1. protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
    2. return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest));
    3. }
  • 默认使用DefaultTokenServices来获取token

    1. public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    2. ... 一系列判断 ,合法性、是否过期等判断
    3. OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
    4. tokenStore.storeAccessToken(accessToken, authentication);
    5. // In case it was modified
    6. refreshToken = accessToken.getRefreshToken();
    7. if (refreshToken != null) {
    8. tokenStore.storeRefreshToken(refreshToken, authentication);
    9. }
    10. return accessToken;
    11. }
  • createAccessToken 核心逻辑

    1. // 默认刷新token 的有效期
    2. private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30; // default 30 days.
    3. // 默认token 的有效期
    4. private int accessTokenValiditySeconds = 60 * 60 * 12; // default 12 hours.
    5. private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
    6. DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(uuid);
    7. token.setExpiration(Date)
    8. token.setRefreshToken(refreshToken);
    9. token.setScope(authentication.getOAuth2Request().getScope());
    10. return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
    11. }

    如上代码,在拼装好token对象后会调用认证服务器配置TokenEnhancer( 增强器) 来对默认的token进行增强。

  • TokenEnhancer.enhance 通过上下文中的用户信息来个性化Token

    1. public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    2. final Map<String, Object> additionalInfo = new HashMap<>(8);
    3. PigxUser pigxUser = (PigxUser) authentication.getUserAuthentication().getPrincipal();
    4. additionalInfo.put("user_id", pigxUser.getId());
    5. additionalInfo.put("username", pigxUser.getUsername());
    6. additionalInfo.put("dept_id", pigxUser.getDeptId());
    7. additionalInfo.put("tenant_id", pigxUser.getTenantId());
    8. additionalInfo.put("license", SecurityConstants.PIGX_LICENSE);
    9. ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    10. return accessToken;
    11. }

基于pig 看下最终的实现效果

Pig 基于Spring Cloud、oAuth2.0开发基于Vue前后分离的开发平台,支持账号、短信、SSO等多种登录,提供配套视频开发教程。
https://gitee.com/log4j/pig

image