1、导入pom.xml依赖
<dependency><groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies> 2、生成和解析令牌类的书写 private static String signKey="infom";
private static long expire=1000L*20;
/*生成JWT令牌*/
public static String generateJwt(Map<String,Object> claims){
String jwt= Jwts.builder()
.signWith(SignatureAlgorithm.HS256,signKey)
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis()+expire))//令牌有效时间
.compact();
return jwt;
}
/*解析令牌*/
public static Claims parseJWT(String jwt){
Claims claims=Jwts.parser()
.setSigningKey(signKey)
.parseClaimsJws(jwt)
.getBody();
return claims;
} 3、在loginController里使用 并生成通过response 给浏览器发送 { "code": 2, "msg": "NOT_LOGIN", "data": null } { "code": 1, "msg": "success", "data": "eyJhbGciOiJIUzI1NiJ9.eyJFbnRlclVzZXJOYW1lIjoiMjAyMjAwMDEiLCJleHAiOjE3MDg4NjA2NTQsIkVudGVyUGFzc3dvcmQiOiIxMjM0NTY3In0.wYvK9ExVvmB5k9IlnfM4CC40NGyHG_Mw9T0VnElwcSU" } 失败和成功,postman接收到的数据 4、拦截校验 过滤器拦截 Filter javaweb三大组件之一 把对资源的请求拦截下来 通用,登录鉴权 拦截器 Interceptor //拦截所有资源
@WebFilter(urlPatterns = "/*")
public class LoginChechedFilter implements Filter {
//拦截方法,只要资源链接被拦截就会触发此方法
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("拦截方法执行");
//放行
filterChain.doFilter(servletRequest,servletResponse);
}
} @ServletComponentScan在Application里加入这个注解,可以扫描到拦截器Filter 在前端添加代码 const jwtToken = res.data.data; // 存储到LocalStorage中 localStorage.setItem("jwtToken", jwtToken); 将token存到浏览器中的localstorage中 fetchData() { // 从LocalStorage中获取JWT令牌 const storedToken = localStorage.getItem("jwtToken"); // 创建一个axios实例,并设置默认请求头 const axiosInstance = axios.create({ headers: { 'Authorization': `Bearer ${storedToken}` , 'Content-Type': 'application/json', // 可以根据需要设置其他头部信息 } }); // 发送GET请求 axiosInstance.get('your_api_endpoint') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error:', error); }); } } }
标签:令牌,String,登录,功能,完整,static,拦截,data,public From: https://www.cnblogs.com/wonder-question/p/18033337