令牌(token)技术
不需要在服务端去保留用户的认证信息或者会话信息。这就意味着基于token认证机制的应用不需要去考虑用户在哪一台服务器登录了
1.基本流程
用户使用用户名密码来请求服务器
服务器进行验证用户的信息
服务器通过验证发送给用户一个token
客户端存储token,并在每次请求时附送上这个token值
服务端验证token值,并返回数据
JWT (全称JSON WEB TOKEN)
1.导入jar包
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.6</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
这个jar包包含了上面三个
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.12.6</version>
</dependency>
2.官网(https://jwt.io/)
3.格式
以json格式传输共享数据(分为三部分,最后三个部分组成的完整json会使用Base64进行编码且以.分割)
Header(头)
用于记录令牌类型以及签名算法等信息
PayLoad(载荷)
存储Http共享数据
Signature(签名)
使用加密算法保证Header与PayLoad的安全性
4.如何使用jwt(生成,校验)
package com.lu.tlias84;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import javax.xml.crypto.Data;
import java.util.Date;
public class TestJwt {
@Test
public void testGenerateJwtToken(){
//1. 构建jwt对象
JwtBuilder builder = Jwts.builder();
//2. 指定header(一般不指定)
//省略使用默认的jwt头
//3. 往payload放置http需要共享的信息,并且指定过期时间
builder.claim("username","count-l");
builder.claim("password","count-l");
Date date = new Date();
builder.issuedAt(date);//token生效时间
builder.expiration(new Date(date.getTime()+60*1000));//指定过期时间
//4. 进行数字签名
String key = "febaa5b6-b818-440a-ad8a-9606ffaafd0c";
//第一个参数是数字签名(需要自己生成)
//第二个参数 加密的签名算法,新版需要保证一定强度(HS256至少要32字节,HS384至少需要84字节,HS512至少要64字节)
builder.signWith(Keys.hmacShaKeyFor(key.getBytes()), Jwts.SIG.HS256);
//生成token
String compact = builder.compact();
System.out.println(compact);
}
@Test
public void testVerifyJwtToken(){
String key = "febaa5b6-b818-440a-ad8a-9606ffaafd0c";
String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImNvdW50LWwiLCJwYXNzd29yZCI6ImNvdW50LWwiLCJpYXQiOjE3MjQzMTUyODUsImV4cCI6MTcyNDMxNTM0NX0.olJzzamV5Pi5qdKCU3p0F19SX_vaD2rSkiLXfrxenVo";
//1.构建jwt解析对象
JwtParserBuilder parser = Jwts.parser();
//2.指定数字签名
JwtParser build = parser.verifyWith(Keys.hmacShaKeyFor(key.getBytes())).build();
//3.指定token
Claims payload = build.parseSignedClaims(token).getPayload();
System.out.println(payload.get("username"));
System.out.println(payload.get("password"));
}
}
解析
public void testVerifyJwtToken(){
String key = "febaa5b6-b818-440a-ad8a-9606ffaafd0c";
String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImNvdW50LWwiLCJwYXNzd29yZCI6ImNvdW50LWwifQ.0HgzrDeIXEOixSV9-08lCLx0sX6m--3ShxYYUpJKhz4";
//1.构建jwt解析对象
JwtParserBuilder parser = Jwts.parser();
//2.指定数字签名
JwtParser build = parser.verifyWith(Keys.hmacShaKeyFor(key.getBytes())).build();
//3.指定token
Claims payload = build.parseSignedClaims(token).getPayload();
System.out.println(payload.get("username"));
System.out.println(payload.get("password"));
}
JWT工具类
package com.lu.tlias84.utils;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.util.Date;
/**
* jwt token 生成与验证(解析)
*/
public class JwtUtil {
private JwtUtil(){}
private static final String SIG = "febaa5b6-b818-440a-ad8a-9606ffaafd0c";
/**
* 生成token
* @param username payload-用户名
* @param password payload-密码
* @param minutes token过期时间,以分钟为单位
* @return token
*/
public static String generateToken(String username,String password,long minutes){
//1.构建jwt对象
//2.指定header(一般省略)
//3.放置payload,以及过期时间和生效时间
//4.进行数字签名
//第一个参数是数字签名(需要自己生成)
//第二个参数 加密的签名算法,新版需要保证一定强度(HS256至少要32字节,HS384至少需要84字节,HS512至少要64字节)
//5.生成token
Date now = new Date();
String token = Jwts.builder()
.claim("username", username)
.claim("password", password)
.issuedAt(now)
.expiration(new Date(now.getTime() + 60 * 1000 * minutes))
.signWith(Keys.hmacShaKeyFor(SIG.getBytes()), Jwts.SIG.HS256)
.compact();
return token;
}
/**
* 验证token
* @param token 生成的令牌
* @return payload中的用户信息
*/
public static JSONObject verifyToken(String token){
//1.构建解析对象
//2.指定数字签名
//3.指定被签名后的token
JwtParser parser = Jwts.parser()
.verifyWith(Keys.hmacShaKeyFor(SIG.getBytes())).build();
Claims payload = parser.parseSignedClaims(token).getPayload();
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", payload.get("username"));
jsonObject.put("password", payload.get("password"));
//TODO: 还没有完成token失效的处理以及 token字符串不和法的处理
return jsonObject;
}
}
使用
package com.lu.tlias84.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.lu.tlias84.entity.Emp;
import com.lu.tlias84.mapper.EmpMapper;
import com.lu.tlias84.po.LoginParam;
import com.lu.tlias84.service.LoginService;
import com.lu.tlias84.utils.JwtUtil;
import com.lu.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Service
public class LoginServiceImpl implements LoginService {
@Resource
private EmpMapper empMapper;
@Override
public ResultUtil login(LoginParam loginParam) {
Emp emp = empMapper.selectEmpByUsername(loginParam.getUsername());
if (Objects.isNull(emp) || !emp.getPassword().equals(loginParam.getPassword())) {
return ResultUtil.fail("用户名或者密码不正确");
}
String token = JwtUtil.generateToken(loginParam.getUsername(), loginParam.getPassword(), 30);
JSONObject json = new JSONObject();
json.put("id", emp.getId());
json.put("username", emp.getUsername());
json.put("password", emp.getPassword());
json.put("token", token);
return ResultUtil.success(json);
}
}
过滤器
1.filter
package com.lu.tlias84.filter;
import com.alibaba.fastjson.JSONObject;
import com.lu.tlias84.entity.Emp;
import com.lu.tlias84.mapper.EmpMapper;
import com.lu.tlias84.utils.JwtUtil;
import com.lu.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
/**
* 登录过滤器,进行登录token拦截
*/
@Slf4j
//@Component
public class LoginFilter implements Filter {
@Resource
private EmpMapper empMapper;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
log.info("初始化过滤器");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("开始执行http请求过滤");
//参数向下转型成HttpServletRequest以及HttpServletResponse
HttpServletRequest sRequest = (HttpServletRequest) request;
HttpServletResponse sResponse = (HttpServletResponse) response;
//放行登录接口
String uri = sRequest.getRequestURI();
if (uri.contains("login")) {
chain.doFilter(request, response);
return;
}
//获取请求头中的token
String token = sRequest.getHeader("token");
//判断是否有token->是否绕过登录
if (Objects.isNull(token)) {
writeErrorResponse(sResponse,"请先登录");
return;
}
//校验token是否过期或者错误
JSONObject jsonObject =null;
try {
jsonObject = JwtUtil.verifyToken(token);
} catch (Exception e) {
writeErrorResponse(sResponse,"token不合法");
return;
}
//TODO: 使用jwt工具类验证token中的数据是否正确
Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))) {
writeErrorResponse(sResponse,"校验不正确");
return;
}
//过滤链对象执行完过滤逻辑之后放行http请求,把request,response重新交给controller(servlet)
chain.doFilter(request, response);
log.info("过滤完成");
}
private static void writeErrorResponse(HttpServletResponse sResponse,String msg) throws IOException {
//设置UTF-8编码
sResponse.setContentType("application/json;charset=utf-8");
sResponse.setCharacterEncoding("UTF-8");
//设置响应状态码
sResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
PrintWriter writer = sResponse.getWriter();
ResultUtil fail = ResultUtil.fail(msg);
//使用fastjson把对象转成json字符串
writer.write(JSONObject.toJSONString(fail));
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
2.流程图
拦截器
1.SpringBoot2.x
编写拦截器
实现HandlerInterceptorAdapter接口
配置拦截器
继承WebMvcConfigurer类器
2.SpringBoot3.x
编写拦截器
实现Handlerlnterceptor接口
package com.lu.tlias84.Interceptor;
import com.alibaba.fastjson.JSONObject;
import com.lu.tlias84.entity.Emp;
import com.lu.tlias84.mapper.EmpMapper;
import com.lu.tlias84.utils.JwtUtil;
import com.lu.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
/**
* springboot提供的登录拦截器
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Resource
private EmpMapper empMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
if (Objects.isNull(token)) {
writeErrorResponse(response,"请先登录");
return false;
}
JSONObject jsonObject =null;
try {
jsonObject = JwtUtil.verifyToken(token);
} catch (Exception e) {
writeErrorResponse(response,"token不合法");
return false;
}
Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))) {
writeErrorResponse(response,"校验不正确");
return false;
}
return true;
}
private static void writeErrorResponse(HttpServletResponse sResponse,String msg) throws IOException {
//设置UTF-8编码
sResponse.setContentType("application/json;charset=utf-8");
sResponse.setCharacterEncoding("UTF-8");
//设置响应状态码
sResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
PrintWriter writer = sResponse.getWriter();
ResultUtil fail = ResultUtil.fail(msg);
//使用fastjson把对象转成json字符串
writer.write(JSONObject.toJSONString(fail));
}
}
配置拦截器
继承WebMvcConfigurationSupport类
package com.lu.tlias84.config;
import com.lu.tlias84.Interceptor.LoginInterceptor;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* springboot配置类
* 一般用来配置拦截器或者跨域配置。。
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Resource
LoginInterceptor loginInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//添加拦截器
registry.addInterceptor(loginInterceptor)
//添加拦截路径
.addPathPatterns("/**")
//排除路劲
.excludePathPatterns("/login");
}
}
面试题
1.过滤器和拦截器有什么区别
过滤器(filter) 与拦截器(Interceptor)的区别:
相同点:执行都在controller(servlet)之前
不同点:
1.技术提供方:过滤器->servlet提供 拦截器 ->spring
2.执行顺序:先执行过滤器 后执行拦截器
3.拦截力度:过滤器拦截力度粗 ->编码转换,时间格式转化
拦截器拦截力度细 ->登录认证,接口日志记录