概述
JWT的作用
认证方式
认证流程
图示:
暴露的问题:
认证流程
图示:
Jwt的优势
本质为一个字符串
token ====> header.payload.singnature
令牌的组成: 标头(header)
、有效负荷(payload)
、签名(singnature)
JWT通常所示:xxxxxx.yyyyyy.zzzzzz
header: 标头通常由两部分组成即令牌的类型(JWT)和使用的算法类型。【通常使用Base64编码组成JWT结构的第一部分】
{
"alg":"HS256",
"typ":"JWT"
}
payload: 有效负载,存储用户的相关的信息和其他数据的声明。【通常使用Base64编码组成JWT结构的第二部分】
{
"username":"qiumin",
"password":"123456"
}
singnature: 签名,与前面两个部分生成JWT,该签名不能让其他人知道,是保证token不被串改,保证信息的安全。【通常使用Base64编码组成JWT结构的第二部分】
header+"."+payload+"."+singnature ---> 组成唯一的token
springboot
<dependency>
<groupId>com.auth0groupId>
<artifactId>java-jwtartifactId>
<version>3.10.3version>
dependency>
@Test
public void contentLoad(){
HashMap<String,Object> map = new HashMap<>();
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,180);
String token = JWT.create()
.withHeader(map) //header
.withClaim("username", "qiumin") //payload
.withClaim("password", "123456") //payload
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("!FhSD!#VDZF%#FDBD"));//签名
System.out.println(token);
}
结果:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cCI6MTY1NzQzODUxNSwidXNlcm5hbWUiOiJxaXVtaW4ifQ.1TIUuWP1d1-vHc71oTw2pH5LAxtCehiiRnaK3tIZob8
@Test
public void Auth(){
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("!FhSD!#VDZF%#FDBD")).build();
DecodedJWT verify = verifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cCI6MTY1NzQzODUxNSwidXNlcm5hbWUiOiJxaXVtaW4ifQ.1TIUuWP1d1-vHc71oTw2pH5LAxtCehiiRnaK3tIZob8");
System.out.println(verify.getHeader());
System.out.println("payload: "+verify.getClaim("username").asString());
System.out.println("payload: "+verify.getClaim("password").asString());
System.out.println("过期时间: "+verify.getExpiresAt());
}
常见的JWT异常:
封装成工具类JwtUtils
package com.qiumin.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
/**
* @author qiumin
* @classname JWTUtils
* @Description love code
* @date 2022-07-10 15:33
*/
public class JwtUtils {
private static final String SING = "!FhSD!#VhDZF%#FDBD";
/**
* 获得Token
* @param map1 header
* @param map2 payload
* */
public static String getToken(Map<String,Object> map1, Map<String,String> map2){
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,180); //过期时间
JWTCreator.Builder builder = JWT.create();
builder.withHeader(map1); //header
map2.forEach((k,v)->{builder.withClaim(k,v);}); //payload
builder.withExpiresAt(instance.getTime()); //过期时间
String token = builder.sign(Algorithm.HMAC256(SING));//签名
return token;
}
/**
* 验证token
* @param token 令牌
* */
public static void verify(String token){
JWTVerifier build = JWT.require(Algorithm.HMAC256(SING)).build();
build.verify(token);
}
/**
* 获取token中的信息
* @param token 令牌
* */
public static DecodedJWT analysis(String token){
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
}
}
拦截器
创建拦截器的类,配置WebMvcConfigurer,将自己的自定义拦截器装配到容器中
package com.qiumin.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiumin.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
/**
* JwtInterceptor拦截器类
*
* @author qiumin
* @classname JwtInterceptor
* @Description love code
* @date 2022-07-14 13:14
*/
public class JwtInterceptor implements HandlerInterceptor {
/**
* 拦截器
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
HashMap<String, Object> map = new HashMap<>();
JwtUtils jwtUtils = new JwtUtils();
try {
jwtUtils.verify(token);
return true;
}catch (SignatureVerificationException e){
e.printStackTrace();
map.put("msg","无效签名!");
}catch (TokenExpiredException e){
e.printStackTrace();
map.put("msg","token过期!");
}catch (AlgorithmMismatchException e){
e.printStackTrace();
map.put("msg","token算法不一致!");
}catch (Exception e){
e.printStackTrace();
map.put("msg","token无效!");
}
map.put("state",false);
response.setContentType("application/json;charset=UTF-8");
//响应给前端
response.getWriter().println(new ObjectMapper().writeValueAsString(map));
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
配置拦截器
package com.qiumin.config;
import com.qiumin.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author qiumin
* @classname InterceptorConfig
* @Description love code
* @date 2022-07-14 13:37
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
.addPathPatterns("/user/test2") //拦截的路径请求
.excludePathPatterns("/user/login"); //放行的请求路径
}
}
qiumin
plements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
.addPathPatterns("/user/test2") //拦截的路径请求
.excludePathPatterns("/user/login"); //放行的请求路径
}
}
**qiumin**