jwt擴展

1、新建擴展類

package com.ireciting.uaaservice.config;

import com.ireciting.uaaservice.pojo.TUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        TUser user = (TUser) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("user_id", user.getUserId());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }
}

 

2、資源服務器獲取擴展信息

新建類轉換類

package com.ireciting.noteservice.config;

import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.stereotype.Component;

import java.util.Map;
/**
 * @author Lv
 * @version 1.0
 * @Description: 定製 AccessToken 轉換器,爲添加額外信息在服務器端獲取做準備
 * @date 2019/6/21 18:51
 */
@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
        OAuth2Authentication authentication
                = super.extractAuthentication(claims);
        authentication.setDetails(claims);
        return authentication;
    }
}

遍歷獲取

/**
     * 獲取UserID
     * @return
     */
    public static long getCurrentUserID() {
        try {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
            Map<String, Object> map = (Map<String, Object>) details.getDecodedDetails();
            for (String key : map.keySet()) {
                if (key.equals("user_id"))
                    return (Long) map.get(key);
            }
        }
        catch (Exception e){
            return -1L;
        }
        return -1L;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章