VUE+SpringBoot前后端分离使用token完成登录验证
1、后端添加token生成的依赖包<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.4.0</version&...
1、后端添加token生成的依赖包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
2、token生成的工具类
public class JwtUtils {
/**
*
* @Title getToken
* @Description 通过用户id与用户密码 生成token
* @param user
* @return
* @return String
*/
public static String getToken(User user) {
String token="";
token= JWT.create().withAudience(user.getUserId()+"")
.sign(Algorithm.HMAC256(user.getPassword()));
return token;
}
/**
*
* @Title getUserId
* @Description 根据token获取userId
* @param token
* @return Integer
*/
public static Integer getUserId(String token) {
Integer userId=null;
try {
String idString = JWT.decode(token).getAudience().get(0);
userId = Integer.parseInt(idString);
} catch (Exception e) {
e.printStackTrace();
}
return userId;
}
/**
*
* @Title checkToken
* @Description 验证token是否正常
* @param token
* @param user
* @return boolean
*/
public static boolean checkToken(String token,User user) {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (Exception e) {
return false;
}
return true;
}
}
3、后端登录成功返回生成的token,前端获取到token,存入sessionStorage中
let v =this; this.axios.post(v.$baseURL+'userLoginController.ajax', this.$qs.stringify({ username: this.username, password: this.$md5(this.password), //md5加密传输 })).then(function (response) { // console.log(response.data); var status =response.data.status; if(status==101){ v.$message.error(response.data.message); }else if(status==100){ sessionStorage.setItem("token",response.data.message); //存入sessionStorage v.$router.push("/AdminView"); } }) ;
4、前端请求拦截器中将token添加到请求头中发送请求
//添加请求拦截器,在请求头中加token axios.interceptors.request.use( config => { if (sessionStorage.getItem('token')) { config.headers.token = sessionStorage.getItem('token'); console.log(sessionStorage.getItem('token')); } return config; }, error => { return Promise.reject(error); });
5、后端拦截器验证token
public class AuthorityIntercepter implements HandlerInterceptor{
@Resource
private UserService service;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
String token = request.getHeader("token");// 从 http 请求头中取出 token
System.out.println(token);
// 执行认证
if (token == null||"".equals(token.trim())) {
return responseData(response);
}
// 获取 token 中的 user id
Integer userId = JwtUtils.getUserId(token);
if(userId==null) {
return responseData(response);
}
//用户不存在的情况 属于作假token进行登录
User user = service.queryByUserId(userId);
if (user == null) {
return responseData(response);
}
// 验证 token
boolean flage = JwtUtils.checkToken(token, user);
//用户存在但是token也不是根据我的规则产生的说明也是假的
if(flage==false) {
return responseData(response);
}
//将验证通过后的用户信息放到请求中,继续往下执行
request.setAttribute("user", user);
return true;
}
//响应数据
public boolean responseData(HttpServletResponse response) throws IOException {
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
JsonMessage json =new JsonMessage(104, "暂未登录!");
String s = JSON.toJSONString(json);
PrintWriter writer = response.getWriter();
writer.println(s);
return false;
}
}
至此完成了使用token进行登录验证的全过程。
更多推荐
所有评论(0)