同clientId多端登录下jwt+auth2+security使用RedisTokenStore刷新token后长token不可用:Invalid refresh token问题

原文链接https://blog.csdn.net/weixin_41546244/article/details/112554788

背景,环境

springSecurity+jwt+auth2

修改前的配置:

@Bean
    public TokenStore redisTokenStore() {
        // 使用redis存储token
        RedisTokenStore redisTokenStore = new RedisCover(connectionFactory);
        // 设置redis token存储中的前缀
        redisTokenStore.setPrefix(RedisKeysConstant.USER_TOKENS);
        return redisTokenStore;
    }

    @Bean
    public DefaultTokenServices tokenService() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        // 配置token存储
        tokenServices.setTokenStore(redisTokenStore());
        // 开启支持refresh_token,此处如果之前没有配置,启动服务后再配置重启服务,可能会导致不返回token的问题,解决方式:清除redis对应token存储
        tokenServices.setSupportRefreshToken(true);
        // 复用refresh_token
        tokenServices.setReuseRefreshToken(true);
        // token有效期,设置2小时
        tokenServices.setAccessTokenValiditySeconds(2 * 60 * 60);
        // refresh_token有效期,设置一周
        tokenServices.setRefreshTokenValiditySeconds(15 * 24 * 60 * 60);

        // 通过TokenEnhancerChain增强器链将jwtAccessTokenConverter(转换成jwt)和jwtTokenEnhancer(往里面加内容加信息)连起来
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);
        tokenServices.setTokenEnhancer(enhancerChain);

        return tokenServices;
    }

redis存储的结构:
在这里插入图片描述

问题描述:

1.正常调用登录接口,返回accessToken,refreshToken,此时使用refreshToken调用刷新token接口,返回的refreshToken无法作为刷新token的参数。
2.A使用账号登录后保存refreshToken,规定时间后accesstoken过期,使用refreshtoken刷新accesstoken,虽然此处可以选择不保留刷新后得到的refreshtoken进行续期,保留之前的旧refreshtoken(也就是长token过期必退出策略),但是多端登录下,另一个人B是使用同账号登录,得到的是A刷新后的token,而1情况问题得到证实。

原因分析

从RedisTokenStore存储的结构以及源码可知,accessToken、refreshToken相互的关系获得的方式存储的key为:access_to_refresh:*,refresh_to_access:*两个key获得。
但是刷新token时候源码可知:
DefaultTokenServices-refreshAccessToken():

@Transactional(noRollbackFor={InvalidTokenException.class, InvalidGrantException.class})
	public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest)
			throws AuthenticationException {

		if (!supportRefreshToken) {
			throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
		}

		OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
		if (refreshToken == null) {
			throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
		}

		OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
		if (this.authenticationManager != null && !authentication.isClientOnly()) {
			// The client has already been authenticated, but the user authentication might be old now, so give it a
			// chance to re-authenticate.
			Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
			user = authenticationManager.authenticate(user);
			Object details = authentication.getDetails();
			authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
			authentication.setDetails(details);
		}
		String clientId = authentication.getOAuth2Request().getClientId();
		if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
			throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
		}

		// clear out any access tokens already associated with the refresh
		// token.
		tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);

		if (isExpired(refreshToken)) {
			tokenStore.removeRefreshToken(refreshToken);
			throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
		}

		authentication = createRefreshedAuthentication(authentication, tokenRequest);

		if (!reuseRefreshToken) {
			tokenStore.removeRefreshToken(refreshToken);
			refreshToken = createRefreshToken(authentication);
		}

		OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
		tokenStore.storeAccessToken(accessToken, authentication);
		if (!reuseRefreshToken) {
			tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
		}
		return accessToken;
	}

注意tokenStore.readRefreshToken这个方法:
RedisTokenStore-readRefreshToken():

	@Override
	public OAuth2RefreshToken readRefreshToken(String tokenValue) {
		byte[] key = serializeKey(REFRESH + tokenValue);
		byte[] bytes = null;
		RedisConnection conn = getConnection();
		try {
			bytes = conn.get(key);
		} finally {
			conn.close();
		}
		OAuth2RefreshToken refreshToken = deserializeRefreshToken(bytes);
		return refreshToken;
	}

可知校验时候是从REFRESHkey(refresh:*) 的值找到refreshtoken;
但是每次刷新token,刷新的token会在此处获得一个新的refreshToken保存到:

private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
		DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
		int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
		if (validitySeconds > 0) {
			token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
		}
		token.setRefreshToken(refreshToken);
		token.setScope(authentication.getOAuth2Request().getScope());

		return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
	}

由于我们有设置增强链:tokenServices.setTokenEnhancer(enhancerChain);则这个方法的必然会重新生成一个新的refreshToken。

思路

1.让每次刷新返回的refreshtoken都保持一开始的,也就是说到点必然退出的策略,但是存在问题,如果一个人A登录得到了长token后开始计时,下一个人登录还是使用之前的token那可能正好在过期时间点,则会退出,舍弃此思路。

2.因为打断点可以看到刷新token追回保存以下几个key值:
refreshAccessToken方法中有:tokenStore.storeAccessToken(accessToken, authentication);
storeAccessToken:

@Override
	public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
		byte[] serializedAccessToken = serialize(token);
		byte[] serializedAuth = serialize(authentication);
		byte[] accessKey = serializeKey(ACCESS + token.getValue());
		byte[] authKey = serializeKey(AUTH + token.getValue());
		byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
		byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
		byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());

		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			if (springDataRedis_2_0) {
				try {
					this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
					this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
					this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}
			} else {
				conn.set(accessKey, serializedAccessToken);
				conn.set(authKey, serializedAuth);
				conn.set(authToAccessKey, serializedAccessToken);
			}
			if (!authentication.isClientOnly()) {
				conn.sAdd(approvalKey, serializedAccessToken);
			}
			conn.sAdd(clientId, serializedAccessToken);
			if (token.getExpiration() != null) {
				int seconds = token.getExpiresIn();
				conn.expire(accessKey, seconds);
				conn.expire(authKey, seconds);
				conn.expire(authToAccessKey, seconds);
				conn.expire(clientId, seconds);
				conn.expire(approvalKey, seconds);
			}
			OAuth2RefreshToken refreshToken = token.getRefreshToken();
			if (refreshToken != null && refreshToken.getValue() != null) {
				byte[] refresh = serialize(token.getRefreshToken().getValue());
				byte[] auth = serialize(token.getValue());
				byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
				byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
				if (springDataRedis_2_0) {
					try {
						this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
						this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
					} catch (Exception ex) {
						throw new RuntimeException(ex);
					}
				} else {
					conn.set(refreshToAccessKey, auth);
					conn.set(accessToRefreshKey, refresh);
				}
				if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
					ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
					Date expiration = expiringRefreshToken.getExpiration();
					if (expiration != null) {
						int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
								.intValue();
						conn.expire(refreshToAccessKey, seconds);
						conn.expire(accessToRefreshKey, seconds);
					}
				}
			}
			conn.closePipeline();
		} finally {
			conn.close();
		}
	}

由此可见并没有在刷新时候保存refresh与refresh_auth两个key。那我们是不是可以重写这个方法?然后把refresh加进去?,我自己有试过:

/*
package com.xzb.springcloud.auth.server.config;

import com.xzb.springcloud.common.constant.RedisKeysConstant;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Date;

*/
/**
 * @author zjh
 * @version 1.0
 * @Description token存储
 * @date 2021-01-12 14:49
 *//*

 */
/*@Configuration*/

public class RedisCover extends RedisTokenStore {
    private static final String ACCESS = "access:";
    private static final String AUTH_TO_ACCESS = "auth_to_access:";
    private static final String AUTH = "auth:";
    private static final String REFRESH_AUTH = "refresh_auth:";
    private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
    private static final String REFRESH = "refresh:";
    private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
    private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
    private static final String UNAME_TO_ACCESS = "uname_to_access:";

    private static final boolean springDataRedis_2_0 = ClassUtils.isPresent(
            "org.springframework.data.redis.connection.RedisStandaloneConfiguration",
            RedisTokenStore.class.getClassLoader());

    private final RedisConnectionFactory connectionFactory;
    private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
    private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();

    private String prefix = RedisKeysConstant.USER_TOKENS;

    private Method redisConnectionSet_2_0;

    public RedisCover(RedisConnectionFactory connectionFactory) {
        super(connectionFactory);
        this.connectionFactory = connectionFactory;
        if (springDataRedis_2_0) {
            this.loadRedisConnectionMethods_2_0();
        }
    }

    @Override
    public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
        this.authenticationKeyGenerator = authenticationKeyGenerator;
    }

    @Override
    public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
        this.serializationStrategy = serializationStrategy;
    }

    @Override
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    private void loadRedisConnectionMethods_2_0() {
        this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(
                RedisConnection.class, "set", byte[].class, byte[].class);
    }

    private RedisConnection getConnection() {
        return connectionFactory.getConnection();
    }

    private byte[] serialize(Object object) {
        return serializationStrategy.serialize(object);
    }

    private byte[] serializeKey(String object) {
        return serialize(prefix + object);
    }

    private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
    }

    private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
    }

    private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
        return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
    }

    private byte[] serialize(String string) {
        return serializationStrategy.serialize(string);
    }

    private String deserializeString(byte[] bytes) {
        return serializationStrategy.deserializeString(bytes);
    }

    private static String getApprovalKey(OAuth2Authentication authentication) {
        String userName = authentication.getUserAuthentication() == null ? ""
                : authentication.getUserAuthentication().getName();
        return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
    }

    private static String getApprovalKey(String clientId, String userName) {
        return clientId + (userName == null ? "" : ":" + userName);
    }
    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        this.setPrefix(RedisKeysConstant.USER_TOKENS);
        byte[] serializedAccessToken = serialize(token);
        byte[] serializedAuth = serialize(authentication);
        byte[] accessKey = serializeKey(ACCESS + token.getValue());
        byte[] authKey = serializeKey(AUTH + token.getValue());
        byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
        byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
        byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
        RedisConnection conn = getConnection();
        try {
            conn.openPipeline();
            if (springDataRedis_2_0) {
                try {
                    this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
                    this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
                    this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                conn.set(accessKey, serializedAccessToken);
                conn.set(authKey, serializedAuth);
                conn.set(authToAccessKey, serializedAccessToken);
            }
            if (!authentication.isClientOnly()) {
                conn.sAdd(approvalKey, serializedAccessToken);
            }
            conn.sAdd(clientId, serializedAccessToken);
            if (token.getExpiration() != null) {
                int seconds = token.getExpiresIn();
                conn.expire(accessKey, seconds);
                conn.expire(authKey, seconds);
                conn.expire(authToAccessKey, seconds);
                conn.expire(clientId, seconds);
                conn.expire(approvalKey, seconds);
            }
            OAuth2RefreshToken refreshToken = token.getRefreshToken();
            if (refreshToken != null && refreshToken.getValue() != null) {
                byte[] refresh = serialize(token.getRefreshToken().getValue());
                byte[] auth = serialize(token.getValue());
                byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
                byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
                byte[] refreshKey = serializeKey(REFRESH + token.getRefreshToken().getValue());
                byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + token.getRefreshToken().getValue());
                if (springDataRedis_2_0) {
                    try {
                        this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
                        this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
                        this.redisConnectionSet_2_0.invoke(conn, refreshKey, refresh);
                        this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, refresh);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                } else {
                    conn.set(refreshToAccessKey, auth);
                    conn.set(accessToRefreshKey, refresh);
                    conn.set(refreshKey, refresh);
                    conn.set(refreshAuthKey, refresh);
                }
                if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                    ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
                    Date expiration = expiringRefreshToken.getExpiration();
                    if (expiration != null) {
                        int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                                .intValue();
                        conn.expire(refreshToAccessKey, seconds);
                        conn.expire(accessToRefreshKey, seconds);
                        conn.expire(refreshKey, seconds);
                        conn.expire(refreshAuthKey, seconds);
                    }
                }
            }
            conn.closePipeline();
        } finally {
            conn.close();
        }
    }
}

这种方式还是存在问题的(1.应该是注入问题重复无设置的prefix;2.就算prefix设置了成功,但是也会导致存储两次,虽然会替换),因为创建时候也会调用。方法不是最好的,舍弃。

@Override
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

3.每次刷新,登录都单独使用accessToken与refreshToken,且旧的保持可用不可以删除,注意这个参数:reuseRefreshToken:注意如下旧的不删除,保持可用:
refreshAccessToken:

if (!reuseRefreshToken) {
			tokenStore.removeRefreshToken(refreshToken);
			refreshToken = createRefreshToken(authentication);
		}

这样的话,无论客户端想要延期还是只用旧的都可以支持:
而且:
refreshAccessToken()-RedisTokenStore下storeRefreshToken()方法:

if (!reuseRefreshToken) {
			tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
		}
@Override
	public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
		byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
		byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
		byte[] serializedRefreshToken = serialize(refreshToken);
		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			if (springDataRedis_2_0) {
				try {
					this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
					this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}
			} else {
				conn.set(refreshKey, serializedRefreshToken);
				conn.set(refreshAuthKey, serialize(authentication));
			}
			if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
				ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
				Date expiration = expiringRefreshToken.getExpiration();
				if (expiration != null) {
					int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
							.intValue();
					conn.expire(refreshKey, seconds);
					conn.expire(refreshAuthKey, seconds);
				}
			}
			conn.closePipeline();
		} finally {
			conn.close();
		}
	}

此正好是保存REFRESH、REFRESH_AUTH两个key的:则重写此方法即可:

package com.xzb.springcloud.auth.server.config;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Set;
import java.util.UUID;

/**
 * @author zjh
 * @version 1.0
 * @Description 刷新token自定义重新新增一个token
 * @date 2021-01-12 16:12
 */
public class DefaultServiceCover extends DefaultTokenServices {

    private boolean supportRefreshToken = true;

    private boolean reuseRefreshToken = true;

    private TokenStore tokenStore;

    private TokenEnhancer accessTokenEnhancer;

    private AuthenticationManager authenticationManager;

    public DefaultServiceCover(TokenStore tokenStore, Boolean supportRefreshToken, Boolean reuseRefreshToken,
                               TokenEnhancer accessTokenEnhancer) {
        this.tokenStore = tokenStore;
        this.supportRefreshToken = supportRefreshToken;
        this.reuseRefreshToken = reuseRefreshToken;
        this.accessTokenEnhancer = accessTokenEnhancer;
    }

    @Override
    @Transactional(noRollbackFor = {InvalidTokenException.class, InvalidGrantException.class})
    public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest)
            throws AuthenticationException {

        if (!supportRefreshToken) {
            throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
        }

        OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
        if (refreshToken == null) {
            throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
        }

        OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
        if (this.authenticationManager != null && !authentication.isClientOnly()) {
            // The client has already been authenticated, but the user authentication might be old now, so give it a
            // chance to re-authenticate.
            Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
            user = authenticationManager.authenticate(user);
            Object details = authentication.getDetails();
            authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
            authentication.setDetails(details);
        }
        String clientId = authentication.getOAuth2Request().getClientId();
        if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
            throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
        }

        // clear out any access tokens already associated with the refresh
        // token.
        tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);

        if (isExpired(refreshToken)) {
            tokenStore.removeRefreshToken(refreshToken);
            throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
        }

        authentication = createRefreshedAuthentication(authentication, tokenRequest);

        if (!reuseRefreshToken) {
            tokenStore.removeRefreshToken(refreshToken);
            refreshToken = createRefreshToken(authentication);
        }

        OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
        tokenStore.storeAccessToken(accessToken, authentication);
        tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
        return accessToken;
    }

    private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) {
        OAuth2Authentication narrowed = authentication;
        Set<String> scope = request.getScope();
        OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
        if (scope != null && !scope.isEmpty()) {
            Set<String> originalScope = clientAuth.getScope();
            if (originalScope == null || !originalScope.containsAll(scope)) {
                throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope
                        + ".", originalScope);
            } else {
                clientAuth = clientAuth.narrowScope(scope);
            }
        }
        narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication());
        return narrowed;
    }

    private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) {
        if (!isSupportRefreshToken(authentication.getOAuth2Request())) {
            return null;
        }
        int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
        String value = UUID.randomUUID().toString();
        if (validitySeconds > 0) {
            return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis()
                    + (validitySeconds * 1000L)));
        }
        return new DefaultOAuth2RefreshToken(value);
    }

    private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
        int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
        if (validitySeconds > 0) {
            token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
        }
        token.setRefreshToken(refreshToken);
        token.setScope(authentication.getOAuth2Request().getScope());

        return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
    }

}

改后的**AuthorizationServerConfig(extends AuthorizationServerConfigurerAdapter)**中:

@Bean
    public DefaultTokenServices tokenService() {
        // 通过TokenEnhancerChain增强器链将jwtAccessTokenConverter(转换成jwt)和jwtTokenEnhancer(往里面加内容加信息)连起来
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);
        DefaultServiceCover tokenServices = new DefaultServiceCover(redisTokenStore(), true,
                true, enhancerChain);
        // 配置token存储
        tokenServices.setTokenStore(redisTokenStore());
        // 开启支持refresh_token,此处如果之前没有配置,启动服务后再配置重启服务,可能会导致不返回token的问题,解决方式:清除redis对应token存储
        tokenServices.setSupportRefreshToken(true);
        // 复用refresh_token
        tokenServices.setReuseRefreshToken(true);
        // token有效期,设置2小时
        tokenServices.setAccessTokenValiditySeconds(2 * 60 * 60);
        // refresh_token有效期,设置一周
        tokenServices.setRefreshTokenValiditySeconds(15 * 24 * 60 * 60);
        tokenServices.setTokenEnhancer(enhancerChain);
        return tokenServices;
    }

问题得到解决

转载注明出处。

首先,需要了解什么是拦截器和 JWT。 拦截器是一个在请求处理之前或之后进行拦截拦截的组件,类似于过滤器,可以对请求进行预处理、后处理等。在 Spring 框架中,可以使用拦截器来实现一些通用的处理逻辑,例如身份验证、日志记录等。 JWT(JSON Web Token)是一种用于身份验证的标准,它可以在用户和服务器之间传递安全可靠的信息,并且不需要在服务器端存储用户的信息。JWT 由三部分组成:头部、载荷和签名。头部包含加密算法和类型,载荷包含用户信息和过期时间等,签名用于验证数据的完整性和真实性。 接下来,我们来实现自定义拦截器和 JWT 身份验证。 1. 创建 Auth0 账号并创建应用 在 Auth0 官网注册账号并创建一个应用,获取应用的客户端 ID 和客户端密钥。 2. 添加 Auth0 Spring Security 集成依赖 在 Maven 或 Gradle 中添加 Auth0 Spring Security 集成依赖,以 Maven 为例: ```xml <dependency> <groupId>com.auth0</groupId> <artifactId>auth0-spring-security-api</artifactId> <version>1.5.0</version> </dependency> ``` 3. 创建 JWTUtils 工具类 在项目中创建 JWTUtils 工具类,用于生成和解析 JWT。 ```java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.Date; public class JWTUtils { private static final long EXPIRE_TIME = 30 * 60 * 1000; // 过期时间,单位毫秒 private static final String TOKEN_SECRET = "secret"; // 密钥 /** * 生成 token * * @param userId 用户 ID * @return token */ public static String createToken(String userId) { Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME); return JWT.create() .withIssuer("auth0") .withClaim("userId", userId) .withExpiresAt(expireAt) .sign(Algorithm.HMAC256(TOKEN_SECRET)); } /** * 验证 token * * @param token token * @return 用户 ID */ public static String verifyToken(String token) { DecodedJWT jwt = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)) .withIssuer("auth0") .build() .verify(token); return jwt.getClaim("userId").asString(); } } ``` 4. 创建 Auth0Config 配置类 在项目中创建 Auth0Config 配置类,用于配置 Auth0 的参数。 ```java import com.auth0.spring.security.api.JwtWebSecurityConfigurer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity public class Auth0Config { @Value(value = "${auth0.apiAudience}") private String apiAudience; @Value(value = "${auth0.issuer}") private String issuer; /** * 配置 Auth0 参数 */ public void configure(HttpSecurity http) throws Exception { JwtWebSecurityConfigurer.forRS256(apiAudience, issuer) .configure(http) .authorizeRequests() .antMatchers("/api/public/**").permitAll() .anyRequest().authenticated(); } } ``` 5. 创建 Auth0Interceptor 拦截器 在项目中创建 Auth0Interceptor 拦截器,用于拦截请求并进行身份验证。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class Auth0Interceptor implements HandlerInterceptor { @Autowired private Auth0Client auth0Client; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { String token = authorizationHeader.substring(7); String userId = JWTUtils.verifyToken(token); if (userId != null) { request.setAttribute("userId", userId); return true; } } response.setStatus(401); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } ``` 6. 创建 Auth0Client 客户端 在项目中创建 Auth0Client 客户端,用于与 Auth0 进行交互,例如获取用户信息等。 ```java import com.auth0.client.auth.AuthAPI; import com.auth0.client.mgmt.ManagementAPI; import com.auth0.exception.Auth0Exception; import com.auth0.json.auth.TokenHolder; import com.auth0.json.mgmt.users.User; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Auth0Client { @Value(value = "${auth0.domain}") private String domain; @Value(value = "${auth0.clientId}") private String clientId; @Value(value = "${auth0.clientSecret}") private String clientSecret; /** * 获取访问令牌 * * @return 访问令牌 * @throws Auth0Exception Auth0 异常 */ public String getAccessToken() throws Auth0Exception { AuthAPI authAPI = new AuthAPI(domain, clientId, clientSecret); TokenHolder tokenHolder = authAPI.requestToken("https://" + domain + "/api/v2/"); return tokenHolder.getAccessToken(); } /** * 根据用户 ID 获取用户信息 * * @param userId 用户 ID * @return 用户信息 * @throws Auth0Exception Auth0 异常 */ public User getUserById(String userId) throws Auth0Exception { ManagementAPI managementAPI = new ManagementAPI(domain, getAccessToken()); return managementAPI.users().get(userId, null).execute(); } } ``` 7. 配置拦截器和认证管理器 在 Spring 配置文件中配置拦截器和认证管理器。 ```xml <!-- 配置拦截器 --> <mvc:interceptor> <mvc:mapping path="/api/**"/> <bean class="com.example.demo.interceptor.Auth0Interceptor"/> </mvc:interceptor> <!-- 配置认证管理器 --> <bean class="org.springframework.security.authentication.AuthenticationManager"/> ``` 8. 创建登录和登出接口 在控制器中创建登录和登出接口,用于生成和验证 JWT。 ```java import com.auth0.exception.Auth0Exception; import com.auth0.json.mgmt.users.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired private Auth0Client auth0Client; /** * 登录接口 * * @param username 用户名 * @param password 密码 * @return token * @throws Auth0Exception Auth0 异常 */ @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password) throws Auth0Exception { // 根据用户名和密码验证用户身份,并获取用户 ID String userId = "user123"; return JWTUtils.createToken(userId); } /** * 登出接口 */ @PostMapping("/logout") public void logout() { // 清除 token } } ``` 以上就是使用自定义拦截器和 Auth0 JWT 实现登录、登出的步骤。通过这种方式,可以实现简单、安全、可靠的用户身份验证,有效地保护用户的数据安全。
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值