Spring Security OAuth 個性化token

冷冷gg發表於2019-02-18

個性化Token 目的

  • 預設通過呼叫 /oauth/token 返回的報文格式包含以下引數
{
    "access_token": "e6669cdf-b6cd-43fe-af5c-f91a65041382",
    "token_type": "bearer",
    "refresh_token": "da91294d-446c-4a89-bdcf-88aee15a75e8",
    "expires_in": 43199, 
    "scope": "server"
}
複製程式碼

並沒包含使用者的業務資訊比如使用者資訊、租戶資訊等。

  • 擴充套件生成包含業務資訊(如下),避免系統多次呼叫,直接可以通過認證介面獲取到使用者資訊等,大大提高系統效能
{
    "access_token":"a6f3b6d6-93e6-4eb8-a97d-3ae72240a7b0",
    "token_type":"bearer",
    "refresh_token":"710ab162-a482-41cd-8bad-26456af38e4f",
    "expires_in":42396,
    "scope":"server",
    "tenant_id":1,
    "license":"made by pigx",
    "dept_id":1,
    "user_id":1,
    "username":"admin"
}
複製程式碼

密碼模式生成Token 原始碼解析

image

​ 主頁參考紅框部分

  • ResourceOwnerPasswordTokenGranter (密碼模式)根據使用者的請求資訊,進行認證得到當前使用者上下文資訊

    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
    	String username = parameters.get("username");
    	String password = parameters.get("password");
    	// Protect from downstream leaks of password
    	parameters.remove("password");
        Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
       ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    		
        userAuth = authenticationManager.authenticate(userAuth);
    
        OAuth2Request storedOAuth2Request =  getRequestFactory().createOAuth2Request(client, tokenRequest);		
    		return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
    複製程式碼
  • 然後呼叫AbstractTokenGranter.getAccessToken() 獲取OAuth2AccessToken

    protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
       return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest));
    }
    複製程式碼
  • 預設使用DefaultTokenServices來獲取token

    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    
    	... 一系列判斷 ,合法性、是否過期等判斷	
    	OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
    		tokenStore.storeAccessToken(accessToken, authentication);
    		// In case it was modified
    		refreshToken = accessToken.getRefreshToken();
    		if (refreshToken != null) {
    			tokenStore.storeRefreshToken(refreshToken, authentication);
    		}
    		return accessToken;
    }
    
    複製程式碼
  • createAccessToken 核心邏輯

    // 預設重新整理token 的有效期
    private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30; // default 30 days.
    // 預設token 的有效期
    private int accessTokenValiditySeconds = 60 * 60 * 12; // default 12 hours.
    
    private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(uuid);
        token.setExpiration(Date)
        token.setRefreshToken(refreshToken);
        token.setScope(authentication.getOAuth2Request().getScope());
        return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
    }
    複製程式碼

    如上程式碼,在拼裝好token物件後會呼叫認證伺服器配置TokenEnhancer( 增強器) 來對預設的token進行增強。

  • TokenEnhancer.enhance 通過上下文中的使用者資訊來個性化Token

    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInfo = new HashMap<>(8);
        PigxUser pigxUser = (PigxUser) authentication.getUserAuthentication().getPrincipal();
        additionalInfo.put("user_id", pigxUser.getId());
        additionalInfo.put("username", pigxUser.getUsername());
        additionalInfo.put("dept_id", pigxUser.getDeptId());
        additionalInfo.put("tenant_id", pigxUser.getTenantId());
        additionalInfo.put("license", SecurityConstants.PIGX_LICENSE);
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
    複製程式碼

基於pig 看下最終的實現效果

Pig 基於Spring Cloud、oAuth2.0開發基於Vue前後分離的開發平臺,支援賬號、簡訊、SSO等多種登入,提供配套視訊開發教程。
gitee.com/log4j/pig

image

相關文章