栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

springboot jwt redis实现token刷新

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot jwt redis实现token刷新

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

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

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

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

初始化一个工程

	org.springframework.boot
	spring-boot-starter-parent
	2.3.2.RELEASE



	
		org.springframework.boot
		spring-boot-starter-test
		test
	
	
	
		org.springframework.boot
		spring-boot-starter-web
		
			
				org.springframework.boot
				spring-boot-starter-tomcat
			
		
	
	
		org.springframework.boot
		spring-boot-starter-freemarker
	
	
		org.springframework.boot
		spring-boot-starter-websocket
	
	
		org.springframework.boot
		spring-boot-starter-undertow
	
	
	
		org.springframework.boot
		spring-boot-starter-data-redis
	
	
		org.apache.commons
		commons-pool2
	
	
	
		com.auth0
		java-jwt
		3.10.3
	



	
		
			org.springframework.boot
			spring-boot-maven-plugin
			
				true
			
		
	

核心的配置
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 {
	
	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 {
	
	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) {

		
		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();
    	
    	
    	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);
    	
    	
    	Map 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()))
    			
    			// .withExpiresAt(new Date(expiresAt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()))
    			// 使用生成的tokenId作为jwt的id
    			.withJWTId(userToken.getId())
    			.sign(Algorithm.HMAC256(this.jwtKey));

    	
    	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())) {

					
					this.objectRedisTemplate.expire(tokenKey, userToken.getRemember() 
							? TimeUnit.DAYS.toSeconds(7) 
							: TimeUnit.MINUTES.toSeconds(30),
								TimeUnit.SECONDS);

					//TODO 把当前用户的身份信息,存储到当前请求的上下文,以便在Controller中获取 (例如存储到:ThreadLocal)
					return true;
				}
			}
		}
		
		
		
		// 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过期了。


原文:https://springboot.io/t/topic/2345

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号