springboot jwt redis实现token刷新

5,273 阅读3分钟

使用jwt的好处就是,服务器不需要维护,存储token的状态。服务器只需要验证Token是否合法就行。确实省了不少事儿。但是弊端也显而易见,就是服务器没法主动让一个Token失效,并且给Token指定了exp过期时间后,不能修改。

配合redis,就可以轻松的解决上面两个问题

  • token的续约
  • 服务器主动失效指定的token

接下来,我会演示一个实现Demo

初始化一个工程

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.3.2.RELEASE</version>
</parent>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
		<exclusions>
			<exclusion>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-tomcat</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-freemarker</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-websocket</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-undertow</artifactId>
	</dependency>
	<!-- redis -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-pool2</artifactId>
	</dependency>
	<!-- jwt -->
	<dependency>
		<groupId>com.auth0</groupId>
		<artifactId>java-jwt</artifactId>
		<version>3.10.3</version>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
				<executable>true</executable>
			</configuration>
		</plugin>
	</plugins>
</build>

核心的配置

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    timeout: 2000
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0

jwt:
  key: "springboot"

redis的配置,大家都熟。jwt.key是自定义的一个配置项,它配置的就是jwt用来签名的key

Token在Redis中的存储方式

需要在Redis中缓存用户的Token,通过自定义一个对象用来描述相关信息。并且这里使用jdk的序列化方式。而不是json

创建Token的描述对象:UserToken

import java.io.Serializable;
import java.time.LocalDateTime;

public class UserToken implements Serializable {

	private static final long serialVersionUID = 8798594496773855969L;
	// token id
	private String id;
	// 用户id
	private Integer userId;
	// ip
	private String ip;
	// 客户端
	private String userAgent;
	// 授权时间
	private LocalDateTime issuedAt;
	// 过期时间
	private LocalDateTime expiresAt;
	// 是否记住我
	private boolean remember;
    // 忽略getter/setter
}

创建:ObjectRedisTemplate

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class ObjectRedisTemplate extends RedisTemplate<String, Object> {
	
	public ObjectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		
		this.setConnectionFactory(redisConnectionFactory);
		
		this.setKeySerializer(StringRedisSerializer.UTF_8);
		this.setValueSerializer(new JdkSerializationRedisSerializer());
	}
}

需要配置到IOC

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class ObjectRedisTemplate extends RedisTemplate<String, Object> {
	
	public ObjectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		this.setConnectionFactory(redisConnectionFactory);
		// key 使用字符串
		this.setKeySerializer(StringRedisSerializer.UTF_8);
		// value 使用jdk的序列化方式
		this.setValueSerializer(new JdkSerializationRedisSerializer());
	}
}

这里不会涉及太多Redis相关的东西,如果不熟悉,那么你只需要记住ObjectRedisTemplate value就是存储的Java对象。

登录的实现逻辑

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import io.springboot.jwt.domain.User;
import io.springboot.jwt.redis.ObjectRedisTemplate;
import io.springboot.jwt.web.support.UserToken;

@RestController
@RequestMapping("/login")
public class LoginController {
	
	@Autowired
	private ObjectRedisTemplate objectRedisTemplate;
	
	@Value("${jwt.key}")
	private String jwtKey;		// 从配置中读取到 jwt 的key

	@PostMapping
	public Object login(HttpServletRequest request,
						HttpServletResponse response,
						@RequestParam("account") String account,
						@RequestParam("password") String password,
						@RequestParam(value = "remember", required = false) boolean remember) {

		/**
		 *忽略验证逻辑,假设用户已经是登录成功的状态,并且他的ID是1 
		 */
		User user = new User(); 
		user.setId(1);
		
		/**
		 * 登录信息
		 */
		String ip = request.getRemoteAddr();							// 客户端ip(如果是反向代理,要根据情况获取实际的ip)
    	String userAgent = request.getHeader(HttpHeaders.USER_AGENT);	// UserAgent
    	
    	// 登录时间
    	LocalDateTime issuedAt = LocalDateTime.now();
    	
    	
    	// 过期时间,如果是“记住我”,则Token有效期是7天,反之则是半个小时
    	LocalDateTime expiresAt = issuedAt.plusSeconds(remember 
    								? TimeUnit.DAYS.toSeconds(7)
    								: TimeUnit.MINUTES.toSeconds(30));
    	
    	// 距离过期时间剩余的秒数
    	int expiresSeconds = (int) Duration.between(issuedAt, expiresAt).getSeconds();
    	
    	/**
    	 * 存储Session
    	 */
    	UserToken userToken = new UserToken();
    	// 随机生成uuid,作为token的id
    	userToken.setId(UUID.randomUUID().toString().replace("-", ""));
    	userToken.setUserId(user.getId());
    	userToken.setIssuedAt(issuedAt);
    	userToken.setExpiresAt(expiresAt);
    	userToken.setRemember(remember);
    	userToken.setUserAgent(userAgent);
    	userToken.setIp(ip);
    	
    	// 序列化Token对象到Redis
    	this.objectRedisTemplate.opsForValue().set("token:" + user.getId(), userToken, expiresSeconds, TimeUnit.SECONDS);
    	
    	/**
    	 * 生成Token信息
    	 */
    	Map<String, Object> jwtHeader = new HashMap <>();
    	jwtHeader.put("alg", "alg");
    	jwtHeader.put("JWT", "JWT");
    	String token = JWT.create()
    			.withHeader(jwtHeader)
    			// 把用户的id写入到token
    			.withClaim("id", user.getId())
    			.withIssuedAt(new Date(issuedAt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()))
    			/**
    			 * 这里不在Token上设置过期时间,过期时间由Redis维护
    			 */
    			// .withExpiresAt(new Date(expiresAt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()))
    			// 使用生成的tokenId作为jwt的id
    			.withJWTId(userToken.getId())
    			.sign(Algorithm.HMAC256(this.jwtKey));

    	/**
    	 * 把Token以Cookie的形式响应客户端
    	 */
    	Cookie cookie = new Cookie("_token", token);
    	cookie.setSecure(request.isSecure());
    	cookie.setHttpOnly(true);
    	// 非记住我的状态情况,cookie生命周期设置为-1,浏览器关闭后就立即删除
    	cookie.setMaxAge(remember ? expiresSeconds : -1);
    	cookie.setPath("/");
    	response.addCookie(cookie);
    	
		return Collections.singletonMap("success", true);
	}
}

允许同一个用户在多出登录

上述代码中,存储Token,使用的是用户的id作为key,那么任何时候,用户只能有一个合法的Token。但是有些场景又是允许用户同时有多个Token,此时可以在redis的key中,添加token的id。

this.objectRedisTemplate.opsForValue().set("token:" + user.getId() + ":" + userToken.getId(), userToken, expiresSeconds, TimeUnit.SECONDS);

如果需要检索出用户的所有Token,可以使用Redis的sacnner,进行扫描。

token:{userId}:*

在拦截器中的验证逻辑

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import io.springboot.jwt.redis.ObjectRedisTemplate;
import io.springboot.jwt.web.support.UserToken;

public class TokenValidateInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOGGER = LoggerFactory.getLogger(TokenValidateInterceptor.class);

	@Autowired
	private ObjectRedisTemplate objectRedisTemplate;

	@Value("${jwt.key}")
	private String jwtKey;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		// 解析 cookie
		Cookie cookie = WebUtils.getCookie(request, "_token");

		if (cookie != null) {

			DecodedJWT decodedJWT = null;

			Integer userId = null;

			try {
				decodedJWT = JWT.require(Algorithm.HMAC256(this.jwtKey)).build().verify(cookie.getValue());
				userId = decodedJWT.getClaim("id").asInt();
			} catch (JWTVerificationException e) {
				LOGGER.warn("解析Token异常:{},token={}", e.getMessage(), cookie.getValue());
			}

			if (userId != null) {

				String tokenKey = "token:" + userId;

				UserToken userToken = (UserToken) objectRedisTemplate.opsForValue().get(tokenKey);

				if (userToken != null && userToken.getId().equals(decodedJWT.getId()) && userId.equals(userToken.getUserId())) {

					/**
					 * 此时Token是合法的Token,需要进行续约操作
					 */
					this.objectRedisTemplate.expire(tokenKey, userToken.getRemember() 
							? TimeUnit.DAYS.toSeconds(7) 
							: TimeUnit.MINUTES.toSeconds(30),
								TimeUnit.SECONDS);

					//TODO 把当前用户的身份信息,存储到当前请求的上下文,以便在Controller中获取 (例如存储到:ThreadLocal)
					return true;
				}
			}
		}
		
		/**
		 * 校验失败。Token不存在/非法的Token/Token已过期
		 */
		
		// TODO 抛出未登录异常,在全局处理器中响应客户端(也可以直接在这里通过Response响应)
		return false;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)	throws Exception {
		// TODO,需要记得清理存储到当前请求的上下文中的用户身份信息
	}
}

很简单的逻辑,通过Cookie读取到token,尝试从Redis中读取到缓存的数据。进行校验,如果校验成功。则刷新Token的过期时间,完成续约。

管理Token

就很简单了,只需要根据用户的id,就可以进行删除/续约操作。服务器可以主动的取消某个Token的授权。 如果需要获取到全部的Token,那么可以借助sacn,通过指定的前缀进行扫描。

配合Redis过期key通知事件,还可以在程序中监听到哪些Token过期了。


原文:springboot.io/t/topic/234…