创建生成和解析token的应用类
package com.lenovo.springboot.utils;
import cn.hutool.core.lang.UUID;
import io.jsonwebtoken.*;
import java.util.Date;
import java.util.Map;
public class JwtUtils {
private static final String secret = "1234567890";
//生成jwt
public static String generateToken(long expire,Map map){
//构建jwt 构造器
JwtBuilder buider = Jwts.builder();
//生成jwt 字符串
return buider
//header
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
//载荷
.setClaims(map)//setClaims 必须放在payload 的顶部
.setId(UUID.randomUUID().toString())
.setIssuer("lenovo")
.setIssuedAt(new Date())
.setSubject("demo")
.setExpiration(new Date(System.currentTimeMillis()+expire))
/* .claim("xx","laolixx")
.claim("yy","laoliyy")
.claim("zz","laolizz")*/
.signWith(SignatureAlgorithm.HS256,secret)
.compact();
}
//生成jwt1
public static String generateToken(long expire){
//构建jwt 构造器
JwtBuilder buider = Jwts.builder();
//生成jwt 字符串
return buider
//header
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
//载荷
.setId(UUID.randomUUID().toString())
.setIssuer("lenovo")
.setIssuedAt(new Date())
.setSubject("demo")
.setExpiration(new Date(System.currentTimeMillis()+expire))
/* .claim("xx","laolixx")
.claim("yy","laoliyy")
.claim("zz","laolizz")*/
.signWith(SignatureAlgorithm.HS256,secret)
.compact();
}
//parse jwt
public static Claims parseToken(String token) {
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
Claims payload = claimsJws.getBody();
return payload;
}
}
添加过滤器
package com.lenovo.springboot.filter;
import com.lenovo.springboot.model.ResponseModel;
import com.lenovo.springboot.utils.JwtUtils;
import com.lenovo.springboot.utils.ResponseUtil;
import io.jsonwebtoken.lang.Strings;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpMethod;
import java.io.IOException;
import java.util.Objects;
@WebFilter(urlPatterns = "/*")
public class JwtFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//直接放行 预检 登录
if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
String requestURI = request.getRequestURI();
if(requestURI.contains("/login")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
//得到请求头信息
String token = request.getHeader("accessToken");
if(!Strings.hasText(token)){
//响应错误提示
ResponseModel rm = new ResponseModel(500,"failure","令牌丢失");
ResponseUtil.write(rm,response);
return;
}
//parse token
try {
JwtUtils.parseToken(token);
} catch (Exception e) {
//响应错误提示
ResponseModel rm = new ResponseModel(401,"failure","令牌过期");
ResponseUtil.write(rm,response);
return;
}
filterChain.doFilter(servletRequest,servletResponse);
}
}
错误相应类
package com.lenovo.springboot.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lenovo.springboot.model.ResponseModel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseUtil {
public static void write(ResponseModel rm, HttpServletResponse response) throws IOException{
//构造响应头
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("utf-8");
//构造输出流
PrintWriter out = response.getWriter();
//输出
out.write(new ObjectMapper().writeValueAsString(rm));
out.close();
}
}
普通响应类
package com.lenovo.springboot.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class ResponseModel<T> implements Serializable {
private Integer code;
private String msg;
private T data;
}
登录调用
package com.lenovo.springboot.controller;
import com.lenovo.springboot.entity.User;
import com.lenovo.springboot.model.ResponseModel;
import com.lenovo.springboot.utils.JwtUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//跨域
@CrossOrigin("*")
@RestController
public class LoginController {
@PostMapping("/login")
public ResponseModel login(@RequestBody User user){
Integer code = 200;
String msg = "success";
String token = null;
if(user.getName().equals("admin") && user.getPassword().equals("123")){
token = JwtUtils.generateToken(1000*60*3);
}else {
code=500;
msg="failure";
}
return new ResponseModel(code,msg,token);
}
}
前端测试 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login page</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
username:<input type="text" name="username" ref="username" autocomplete="off"/><br/>
password:<input type="password" name="password" ref="password"/><br/>
<input type="button" value="login" @click="submit"/>
</div>
<script>
const appConfig = {
methods:{
submit(){
let url = "http://localhost:8081/login";
axios.post(url,{name:this.$refs.username.value,password:this.$refs.password.value})
.then(res=>{
if(res.data.code==200){
console.log(res.data.data);
sessionStorage.setItem("accessToken",res.data.data);
location.href="blog.html";
}
})
}
}
}
const app=Vue.createApp(appConfig);
app.mount("#app");
</script>
</body>
</html>
前端测试 验证token
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>blog page</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
title:<input type="text" name="blogTitle" ref="blogTitle" autocomplete="off"/><br/>
content:<textarea name="blogContent" ref="blogContent" autocomplete="off"></textarea><br/>
<input type="button" value="submit" @click="submit"/>
</div>
<script>
const appConfig = {
methods:{
submit(){
let url = "http://localhost:8081/blog";
let token=null;
if(sessionStorage.getItem("accessToken")!= null){
token =sessionStorage.getItem("accessToken");
}
axios.post(url,{},{headers:{accessToken:token}})
//axios.post(url)
.then(res=>{
console.log(res.data.data);
})
}
}
}
const app=Vue.createApp(appConfig);
app.mount("#app");
</script>
</body>
</html>
文章评论