前言:
学习过程观看视频:编程不良人[JWT认证原理、流程整合springboot实战应用,前后端分离认证的解决方案!]
https://www.bilibili.com/video/BV1i54y1m7cP?p=1
欢迎大家支持噢,很良心的老师了
以下内容均为个人学习笔记,若有错误望各位大佬不吝赐教!
源码在个人博客中心的资源里面提供给大家了!
1、编写拦截器
package com.zjl.interceptors;
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.zjl.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
/**
* Created by zjl
* 2020/11/12
**/
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HashMap<String, Object> map = new HashMap<>();
//获取请求头中token
String token = request.getHeader("token");
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);
//将map转化为json,相应给前端
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
2、注册拦截器
package com.zjl.config;
import com.zjl.interceptors.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created by zjl
* 2020/11/12
**/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/user/test") //拦截test接口
.excludePathPatterns("/user/login"); //放行login接口
}
}
3、更改/user/test里面的方法,不需要再在里面编写验证token的代码了。
@PostMapping("/user/test")
public Map<String,Object> test(HttpServletRequest request){
HashMap<String, Object> map = new HashMap<>();
//处理自己的业务逻辑
String token = request.getHeader("token");
DecodedJWT verify = JWTUtils.verify(token);
log.info("用户名:[{}]",verify.getClaim("name").asString());
log.info("密码:[{}]",verify.getClaim("password").asString());
map.put("state",true);
map.put("msg","请求成功!");
return map;
}
4、验证
1、请求/user/test接口,不添加token。
2、请求/user/login接口,获取token。
3、请求/user/test接口,添加token。