在上一节已经提到了传统Session认证和JWT认证内容,这一节对JWT进行更加详细的了解。
一 JWT介绍
1、传统的session认证
1.1 传统session认证流程
1.用户向服务器发送用户名和密码 2.服务器通过验证后,在当前对话(session)中保存相关数据,如用户角色,登录时间等 3.服务器向用户返回一个session_id,写入用户的Cookie 4.用户随后的每一次请求,都会通过Cookie,将session_id传回服务器 5.服务器收到session_id,找到前期保存的数据,由此得知用户的身份
1.2 传统session认证缺陷
- 服务器端存储开销:Session需要在服务器端存储用户状态信息,占用服务器内存资源,而JWT是无状态的,不需要服务器存储会话信息。
- 扩展性问题:在分布式或集群环境中,Session需要在多个服务器间共享,增加了系统复杂性和网络开销,而JWT可以轻松跨服务使用。
- CORS支持:Session认证在跨域场景下处理复杂,需要额外配置,而JWT天然支持跨域请求(JWT是无状态的,不需要存储会话状态,任务服务器都可以验证和解析jWT且JWT通过HTTP头部传递,而不是依赖Cookie但还是需要处理CORS,不过是更加简单直接)。
- 移动端支持:Session在移动应用中支持不好,而JWT更适合移动设备和API认证。
- 性能:JWT避免了服务器端的Session查询操作,减少了数据库或缓存的访问次数。
2、JWT认证
2.1 JWT认证流程
1.用户带着用户名,密码请求服务器 2.服务器对用户信息进行验证 3.通过验证后服务器给用户返回一个token 4.客户端存储token,并在每次请求时附送上这个token值 5.服务端验证token值并返回数据
2.2 JWT的构成
Header(头部)
- 包含令牌类型(typ: "JWT")和签名算法(如 alg: HS256)
- 这部分JSON数据会被Base64编码
Payload(载荷)
- 包含声明(claims),即实际要传递的数据
- 包括用户信息、过期时间等标准字段或自定义字段
- 同样经过Base64编码,但未加密,因此不应存放敏感信息
Signature(签名)
- 用于验证令牌的完整性和真实性
- 通过签名算法及密钥secret对Header和Payload的组合进行签名
- 确保Token在传输过程中未被篡改
这三部分通过Base64编码后用点(.)连接,形成最终的JWT令牌格式:
Base64(Header).Base64(Payload).Base64(Signature) secret保存在服务器端,jwt的签发也是在服务器端生成的,secret就是用来进行jwt的签发和jwt的验证。(所以secret就是服务端的私钥,不能泄露出去)
二 JWT实现
我们先来看ruoyi-framework模块com.ruoyi.framework.web.service下的TokenService
java
package com.ruoyi.framework.web.service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
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.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* token验证处理
*
* @author ruoyi
*/
@Component
public class TokenService
{
private static final Logger log = LoggerFactory.getLogger(TokenService.class);
// 令牌自定义标识
@Value("${token.header}")
private String header;
// 令牌秘钥
@Value("${token.secret}")
private String secret;
// 令牌有效期(默认30分钟)
@Value("${token.expireTime}")
private int expireTime;
// 定义1秒
protected static final long MILLIS_SECOND = 1000;
// 定义1分钟
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
// 定义20分钟
private static final Long MILLIS_MINUTE_TWENTY = 20 * 60 * 1000L;
@Autowired
private RedisCache redisCache;
/**
* 获取用户身份信息
*
* @return 用户信息
*/
public LoginUser getLoginUser(HttpServletRequest request)
{
// 获取请求携带的令牌
String token = getToken(request);
if (StringUtils.isNotEmpty(token))
{
try
{
Claims claims = parseToken(token);
// 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
// 拼接redis中的userKey
String userKey = getTokenKey(uuid);
// 从redis中获取登录信息
LoginUser user = redisCache.getCacheObject(userKey);
return user;
}
catch (Exception e)
{
log.error("获取用户信息异常'{}'", e.getMessage());
}
}
return null;
}
/**
* 设置用户身份信息
*/
public void setLoginUser(LoginUser loginUser)
{
// 用户信息且其中token不为空时
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
{
// 刷新token有效期
refreshToken(loginUser);
}
}
/**
* 删除用户身份信息
*/
public void delLoginUser(String token)
{
if (StringUtils.isNotEmpty(token))
{
String userKey = getTokenKey(token);
// 从redis中删除该用户信息
redisCache.deleteObject(userKey);
}
}
/**
* 创建令牌
*
* @param loginUser 用户信息
* @return 令牌
*/
public String createToken(LoginUser loginUser)
{
// 获取随机uuid
String token = IdUtils.fastUUID();
// set进用户信息的token中
loginUser.setToken(token);
// set用户信息
setUserAgent(loginUser);
// 将用户信息存到redis中
refreshToken(loginUser);
// 构造claims 生成JWT Token
Map<String, Object> claims = new HashMap<>();
claims.put(Constants.LOGIN_USER_KEY, token);
claims.put(Constants.JWT_USERNAME, loginUser.getUsername());
return createToken(claims);
}
/**
* 验证令牌有效期,相差不足20分钟,自动刷新缓存
*
* @param loginUser 登录信息
* @return 令牌
*/
public void verifyToken(LoginUser loginUser)
{
// 获取用户信息中的过期时间
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TWENTY)
{
refreshToken(loginUser);
}
}
/**
* 刷新令牌有效期
*
* @param loginUser 登录信息
*/
public void refreshToken(LoginUser loginUser)
{
loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
// 根据uuid将loginUser缓存
String userKey = getTokenKey(loginUser.getToken());
// set进redis
redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
}
/**
* 设置用户代理信息
*
* @param loginUser 登录信息
*/
public void setUserAgent(LoginUser loginUser)
{
// 解析请求头中的User-Agent信息
UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
// 获取用户登录ip地址
String ip = IpUtils.getIpAddr();
// 将ip地址,登录地点,登录浏览器,操作系统信息set进loginUser
loginUser.setIpaddr(ip);
loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
loginUser.setBrowser(userAgent.getBrowser().getName());
loginUser.setOs(userAgent.getOperatingSystem().getName());
}
/**
* 从数据声明生成令牌
*
* @param claims 数据声明
* @return 令牌
*/
private String createToken(Map<String, Object> claims)
{
String token = Jwts.builder()
.setClaims(claims)
// 使用HS512签名,密钥生成JWT Token
.signWith(SignatureAlgorithm.HS512, secret).compact();
return token;
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return 数据声明
*/
private Claims parseToken(String token)
{
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
/**
* 从令牌中获取用户名
*
* @param token 令牌
* @return 用户名
*/
public String getUsernameFromToken(String token)
{
Claims claims = parseToken(token);
return claims.getSubject();
}
/**
* 获取请求token
*
* @param request
* @return token
*/
private String getToken(HttpServletRequest request)
{
// 从请求头中获取token
String token = request.getHeader(header);
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
{
token = token.replace(Constants.TOKEN_PREFIX, "");
}
return token;
}
private String getTokenKey(String uuid)
{
// 生成tokenKey
return CacheConstants.LOGIN_TOKEN_KEY + uuid;
}
}
其中parseToken方法是从前端穿来的JWT Token中解析出用户登录时的uuid以及用户名,如:
请求携带的token为:eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImxvZ2luX3VzZXJfa2V5IjoiOTE4ODY2YzEtNzU2YS00OWFiLWJmYzUtNWIwYWQ5ODBmMjc3In0.O27MTE-bZwQJ8Sp3IRmyvj3zFgI1SXFcflaw4H82efQnLeGx4Y67aPL5rNGGAcEAvOhQk7dIfllfVcrXq2JO-g
解析出的Claims为: {sub=admin, login_user_key=918866c1-756a-49ab-bfc5-5b0ad980f277}
我们再从登录流程中查看JWT的实现,首先是ruoyi-admin模块com.ruoyi.web.controller.system下的登录接口的登录方法
java
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody)
{
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
接口中的登录方法调用了SysLoginService的login方法生成token并放到ajax中返回给前端
java
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid)
{
// 验证码校验
validateCaptcha(username, code, uuid);
// 登录前置校验
loginPreCheck(username, password);
// 用户验证
Authentication authentication = null;
try
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage());
}
}
finally
{
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);
}
在最后调用了TokenService的createToken方法返回了生成的JWT token。
浏览器中的token
redis中登录信息的key value

三 JWT过滤器
在spring security配置 SecurityConfig类里面我们在httpSecurity中新增了自定义的JWT过滤器并在UsernamePasswordAuthenticationFilter之前执行。
java
/**
* token认证过滤器
*/
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
@Bean
protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception
{
return httpSecurity
......
// 添加JWT filter
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
......
.build();
}
我们来看一下这个自定义的JWT过滤器
java
package com.ruoyi.framework.security.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
/**
* token过滤器 验证token有效性
*
* @author ruoyi
*/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
@Autowired
private TokenService tokenService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException
{
// 从请求中获取用户信息
LoginUser loginUser = tokenService.getLoginUser(request);
// 如果用户信息不为null且上下文中Authentication认证为null
if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
{
// 验证token 并刷过期时间
tokenService.verifyToken(loginUser);
// 创建UsernamePasswordAuthenticationToken对象,设置用户信息和权限
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// 将请求,用户,权限等信息set进 SecurityContextHolder上下文
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
// 继续执行过滤器链,处理后续请求
chain.doFilter(request, response);
}
}
其中JwtAuthenticationTokenFilter继承了OncePerRequestFilter,OncePerRequestFilter会确保一次请求只会通过一次。