spring cloud oauth2 jwt 自定义拓展


spring cloud oauth2 jwt 自定义拓展

**************************

相关类及接口

TokenEnhancer:token增强接口

public interface TokenEnhancer {
    OAuth2AccessToken enhance(OAuth2AccessToken var1, OAuth2Authentication var2);
}

OAuth2AccessToken

public interface OAuth2AccessToken {
    String BEARER_TYPE = "Bearer";
    String OAUTH2_TYPE = "OAuth2";
    String ACCESS_TOKEN = "access_token";
    String TOKEN_TYPE = "token_type";
    String EXPIRES_IN = "expires_in";
    String REFRESH_TOKEN = "refresh_token";
    String SCOPE = "scope";

    Map<String, Object> getAdditionalInformation();
    Set<String> getScope();
    OAuth2RefreshToken getRefreshToken();
    String getTokenType();
    boolean isExpired();
    Date getExpiration();
    int getExpiresIn();
    String getValue();
}

DefaultOAuth2AccessToken:默认的token实现类

public class DefaultOAuth2AccessToken implements Serializable, OAuth2AccessToken {
    private static final long serialVersionUID = 914967629530462926L;
    private String value;
    private Date expiration;
    private String tokenType;
    private OAuth2RefreshToken refreshToken;
    private Set<String> scope;
    private Map<String, Object> additionalInformation;

*************
构造方法

    public DefaultOAuth2AccessToken(String value) {
        this.tokenType = "Bearer".toLowerCase();
        this.additionalInformation = Collections.emptyMap();
        this.value = value;
    }

    public DefaultOAuth2AccessToken(OAuth2AccessToken accessToken) {

*************
普通方法

    public void setValue(String value) {
    public void setExpiration(Date expiration) {
    public void setTokenType(String tokenType) {
    public void setRefreshToken(OAuth2RefreshToken refreshToken) {
    public void setScope(Set<String> scope) {
    public void setAdditionalInformation(Map<String, Object> additionalInformation) {

    public String getValue() {
    public int getExpiresIn() {
    public Date getExpiration() {
    public String getTokenType() {
    public OAuth2RefreshToken getRefreshToken() {
    public Set<String> getScope() {
    public Map<String, Object> getAdditionalInformation() {

    public boolean isExpired() {
    public static OAuth2AccessToken valueOf(Map<String, String> tokenParams) {

OAuth2Authentication:认证信息

public class OAuth2Authentication extends AbstractAuthenticationToken {
    private static final long serialVersionUID = -4809832298438307309L;
    private final OAuth2Request storedRequest;
    private final Authentication userAuthentication;

*************
构造方法

    public OAuth2Authentication(OAuth2Request storedRequest, Authentication userAuthentication) {

*************
普通方法

    public Object getPrincipal() {
    public boolean isClientOnly() {
    public OAuth2Request getOAuth2Request() {
    public Authentication getUserAuthentication() {
    public boolean isAuthenticated() {
    public void eraseCredentials() {

TokenEnhancerChain:可添加多个tokenEnhancer

public class TokenEnhancerChain implements TokenEnhancer {
    private List<TokenEnhancer> delegates = Collections.emptyList();

    public TokenEnhancerChain() {
    }

    public void setTokenEnhancers(List<TokenEnhancer> delegates) {
        this.delegates = delegates;
    }

    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        OAuth2AccessToken result = accessToken;

        TokenEnhancer enhancer;
        for(Iterator var4 = this.delegates.iterator(); var4.hasNext(); result = enhancer.enhance(result, authentication)) {
            enhancer = (TokenEnhancer)var4.next();
        }

        return result;
    }
}

**************************

示例

资源服务器配置参spring cloud oauth2 jwt 使用示例

********************

认证服务器

JwtTokenEnhancer

@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String,Object> map=new HashMap<>();
        map.put("extension","jwt 拓展信息");
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(map);

        return oAuth2AccessToken;
    }
}

OAuth2ServerConfiguration:认证服务器配置

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private UserService userService;

    @Resource
    private JwtTokenStore jwtTokenStore;

    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Resource
    private JwtTokenEnhancer jwtTokenEnhancer;

    public TokenEnhancerChain initTokenEnhancerChain(){
        TokenEnhancerChain tokenEnhancerChain=new TokenEnhancerChain();

        List<TokenEnhancer> list=new ArrayList<>();
        list.add(jwtTokenEnhancer);          //添加自定义tokenEnhancer
        list.add(jwtAccessTokenConverter);   //将token转换为jwt
        tokenEnhancerChain.setTokenEnhancers(list);

        return tokenEnhancerChain;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
        authorizationServerEndpointsConfigurer
                .tokenStore(jwtTokenStore)
                .accessTokenConverter(jwtAccessTokenConverter) //添加tokenConverter
                .tokenEnhancer(initTokenEnhancerChain())   //添加tokenEnhancerChain
                .authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("user")
                .secret(passwordEncoder.encode("123456"))
                .authorizedGrantTypes("authorization_code","refresh_token")
                .redirectUris("http://localhost:8082/redirect")
                .accessTokenValiditySeconds(3000)
                .autoApprove(true)
                .scopes("user");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("isAuthenticated()")    //获取token
                .checkTokenAccess("isAuthenticated()"); //验证token
    }
}

**************************

使用测试

********************

获取jwt

localhost:8081/oauth/authorize

查询参数:client_id=user&response_type=code&redirect_uri=http://localhost:8082/redirect

         

token解码

        

说明:自定义拓展信息extension已经添加到token中

发布了337 篇原创文章 · 获赞 92 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43931625/article/details/104218963