目录
一、WT生成token
1、JWT依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
2、Token工具类
package com.example.demo.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import com.sun.javafx.scene.traversal.Algorithm;
import java.util.Date;
public class TokenUtils {
public static String genToken(String userId,String sign){
return JWT.create().withAudience(userId)
.withExpiresAt(DateUtil.offsetHour(new Date(),2))
.sign(Algorithm.HMAC256(sign));
}
}
二、SpringBoot拦截器拦截token
1、登录service设置token
package com.example.demo.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.Constants;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.User;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.utils.TokenUtils;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author cizhu
* @since 2023-11-12
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Override
public UserDto login(UserDto userDto) {
User one = getUserInfo(userDto);
if (one != null) {
BeanUtil.copyProperties(one, userDto, true);
String token = TokenUtils.genToken(one.getId().toString(),one.getPassword());
userDto.setToken(token);
return userDto;
} else {
throw new ServiceException(Constants.CODE_600, "用户名或密码错误"); //自定义异常
}
}
// List<User> list = list(queryWrapper);
// return list.size()!=0 ;
// }
@Override
public User register(UserDto userDto) {
User one = getUserInfo(userDto);
if (one == null) {
one = new User();
BeanUtil.copyProperties(userDto, one, true);
save(one);
} else {
throw new ServiceException(Constants.CODE_600, "用户已存在");
}
return one;
}
private User getUserInfo(UserDto userDto) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username", userDto.getUsername());
queryWrapper.eq("password", userDto.getPassword());
User one;
try {
one = getOne(queryWrapper);
} catch (Exception e) {
throw new ServiceException(Constants.CODE_500, "系统异常"); //自定义异常
}
return one;
}
}
2、定义拦截器
package com.example.demo.common.interceptor;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.demo.common.AuthAccess;
import com.example.demo.common.Constants;
import com.example.demo.entity.User;
import com.example.demo.exception.ServiceException;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.demo.common.AuthAccess;
@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
if (!(handler instanceof HandlerMethod)){
return true;
}else {
HandlerMethod h = (HandlerMethod) handler;
AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
if (authAccess !=null){
return true;
}
}
if (StrUtil.isBlank(token)){
throw new ServiceException(Constants.CODE_401,"无token,请重新登录");
}
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
}catch (JWTDecodeException j){
throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录");
}
//根据token中userId查询数据库
User user = userService.getById(userId);
if (user == null){
throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录");
}
//验证token
JWTVerifier jwtVerifer =JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try{
jwtVerifer.verify(token);
}catch (JWTVerificationException e){
throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录");
}
return true;
}
}
3、拦截器配置类
package com.example.demo.config;
import com.example.demo.common.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private JwtInterceptor jwtInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**") //拦截所有请求,通过判断token是否合法来决定是否需要登录
.excludePathPatterns("/user/login","/user/register","/**/export","/**/import","/file/**")
.excludePathPatterns("/**/*.hmtl","/**/*.js","/**/*.css");
}
}
三、前端token拦截校验
1、前端request.js请求拦截器拦截token。
//request拦截器
//可以请求发送前对请求做一些处理
request.interceptors.request.use(config=>{
config.headers['Content-Type'] = 'application/json;charset=utf-8';
let user = localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")):null
if (user) {
config.headers['token'] = user.token;
}
return config
},error=>{
return Promise.reject(error)
});
2、token验证不通过给出提示
//response拦截器
request.interceptors.response.use(
response=>{
let res =response.data;
if(response.config.responseType === 'blob'){
return res
}
if(typeof res ==='String'){
res = res ?JSON.parse(res):res
}
//当权限校验不通过,给出提示
if(res.code=='401'){
ElementUI.Message({
message:res.msg,
type:'error'
})
}
return res
},error =>{
console.log('err'+error)
return Promise.reject(error)
}
四、后台获取用户信息
//获取当前用户信息
public static User getCurrentUser(){
try{
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
if (StrUtil.isBlank(token)){
String userId = JWT.decode(token).getAudience().get(0);
return staticUserService.getById(userId);
}
}catch (Exception e){
return null;
}
return null;
}