mirror of
				https://github.com/suyiiyii/SIMS.git
				synced 2025-11-04 15:54:52 +08:00 
			
		
		
		
	jwtUtils
This commit is contained in:
		
							parent
							
								
									c5358cd33e
								
							
						
					
					
						commit
						ffd79f9727
					
				@ -10,7 +10,7 @@ Super Invincible Management System
 | 
			
		||||
5. git fetch origin && git merge origin/main: 拉取远程仓库的最新代码并合并到当前分支
 | 
			
		||||
6. git push origin xxx: 推送当前分支到远程仓库
 | 
			
		||||
7. 提 PR
 | 
			
		||||
8. require review: 请求review
 | 
			
		||||
8. require review: 请求reviewpush
 | 
			
		||||
9. merge: 合并 PR
 | 
			
		||||
10. delete: 删除分支
 | 
			
		||||
 
 | 
			
		||||
 | 
			
		||||
@ -1,10 +1,6 @@
 | 
			
		||||
package top.suyiiyii.sims.common;
 | 
			
		||||
 | 
			
		||||
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 jakarta.annotation.Resource;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
@ -13,6 +9,7 @@ import org.springframework.web.servlet.HandlerInterceptor;
 | 
			
		||||
import top.suyiiyii.sims.entity.User;
 | 
			
		||||
import top.suyiiyii.sims.exception.ServiceException;
 | 
			
		||||
import top.suyiiyii.sims.mapper.UserMapper;
 | 
			
		||||
import top.suyiiyii.sims.utils.JwtUtils;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @Author tortoise
 | 
			
		||||
@ -32,12 +29,12 @@ public class JwtInterceptor implements HandlerInterceptor {
 | 
			
		||||
        // 从 Authorization 头中获取 token
 | 
			
		||||
        String token = request.getHeader("Authorization");
 | 
			
		||||
        if (token != null && token.startsWith("Bearer ")) {
 | 
			
		||||
            token = token.substring(7); // 去除 "Bearer " 前缀
 | 
			
		||||
            token = token.substring(7);
 | 
			
		||||
            // 去除 "Bearer " 前缀
 | 
			
		||||
        } else {
 | 
			
		||||
            // 如果 Authorization 头中没有 token,则尝试从请求参数中获取
 | 
			
		||||
            token = request.getParameter("token");
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 如果不是映射到方法直接通过
 | 
			
		||||
        if (handler instanceof HandlerMethod) {
 | 
			
		||||
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
 | 
			
		||||
@ -45,17 +42,14 @@ public class JwtInterceptor implements HandlerInterceptor {
 | 
			
		||||
                return true;
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 执行认证
 | 
			
		||||
        if (StrUtil.isBlank(token)) {
 | 
			
		||||
            throw new ServiceException("401", "请登录");//权限错误
 | 
			
		||||
            //权限错误
 | 
			
		||||
            throw new ServiceException("401", "请登录");
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 获取 token 中的 user id
 | 
			
		||||
        String userId;
 | 
			
		||||
        try {
 | 
			
		||||
            userId = JWT.decode(token).getAudience().get(0);
 | 
			
		||||
        } catch (JWTDecodeException j) {
 | 
			
		||||
        String userId= JwtUtils.extractUserId(token);
 | 
			
		||||
        if (userId == null) {
 | 
			
		||||
            throw new ServiceException("401", "请登录");
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
@ -63,12 +57,8 @@ public class JwtInterceptor implements HandlerInterceptor {
 | 
			
		||||
        if (user == null) {
 | 
			
		||||
            throw new ServiceException("401", "请登录");
 | 
			
		||||
        }
 | 
			
		||||
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();//加密,认证
 | 
			
		||||
//jwtVerifier  验证器
 | 
			
		||||
        try {
 | 
			
		||||
            jwtVerifier.verify(token);
 | 
			
		||||
        } catch (JWTDecodeException e) {
 | 
			
		||||
 | 
			
		||||
        // 验证 token 的有效性
 | 
			
		||||
        if (!JwtUtils.verifyToken(token, user.getPassword())) {
 | 
			
		||||
            throw new ServiceException("401", "请登录");
 | 
			
		||||
        }
 | 
			
		||||
        return true;
 | 
			
		||||
 | 
			
		||||
@ -73,6 +73,24 @@ public class UserController {
 | 
			
		||||
            userService.addUser(user);
 | 
			
		||||
 | 
			
		||||
        return Result.success();
 | 
			
		||||
    }
 | 
			
		||||
    @PostMapping("/delete")
 | 
			
		||||
    public Result delete(@RequestBody User user) {
 | 
			
		||||
        userService.deleteUser(user.getId());
 | 
			
		||||
        return Result.success("删除成功");
 | 
			
		||||
    }
 | 
			
		||||
    @PostMapping("/update")
 | 
			
		||||
    public Result update(@RequestBody User user) {
 | 
			
		||||
        userService.updateUser(user);
 | 
			
		||||
        return Result.success("更新成功");
 | 
			
		||||
    }
 | 
			
		||||
    @PostMapping("/select")
 | 
			
		||||
    public Result select(@RequestBody User user) {
 | 
			
		||||
        return Result.success(userService.selectById(user.getId()));
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
    @PostMapping("/selectByUsername")
 | 
			
		||||
    public Result selectByUsername(@RequestBody User user) {
 | 
			
		||||
        return Result.success(userService.selectByUsername(user.getUsername()));
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -49,10 +49,10 @@ public interface UserMapper extends BaseMapper<User> {
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 根据ID查询用户信息
 | 
			
		||||
     * @param userId 用户ID
 | 
			
		||||
     * @param id 用户ID
 | 
			
		||||
     * @return 用户对象
 | 
			
		||||
     */
 | 
			
		||||
    @Select("SELECT id, user_id, username, password, name, email, `group` from user WHERE user_id = #{userId}")
 | 
			
		||||
    @Select("SELECT id, user_id, username, password, name, email, `group` from user WHERE id = #{Id}")
 | 
			
		||||
    User selectByUserId(Integer userId);
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
 | 
			
		||||
@ -2,14 +2,14 @@ package top.suyiiyii.sims.service;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
import jakarta.annotation.Resource;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Autowired;
 | 
			
		||||
import org.springframework.stereotype.Service;
 | 
			
		||||
 | 
			
		||||
import top.suyiiyii.sims.common.Result;
 | 
			
		||||
import top.suyiiyii.sims.entity.User;
 | 
			
		||||
import top.suyiiyii.sims.exception.ServiceException;
 | 
			
		||||
import top.suyiiyii.sims.mapper.UserMapper;
 | 
			
		||||
import top.suyiiyii.sims.utils.TokenUtils;
 | 
			
		||||
import top.suyiiyii.sims.utils.JwtUtils;
 | 
			
		||||
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
@ -30,8 +30,8 @@ public class UserService {
 | 
			
		||||
        userMapper.addUser(user);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public User selectByUserId(int id) {
 | 
			
		||||
        return userMapper.selectByUserId(id);
 | 
			
		||||
    public User selectById(int id) {
 | 
			
		||||
        return userMapper.selectById(id);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public void updateUser(User user) {
 | 
			
		||||
@ -54,7 +54,7 @@ public class UserService {
 | 
			
		||||
        if (!dbUser.getPassword().equals(user.getPassword())) {
 | 
			
		||||
            throw new ServiceException("密码或用户名错误");
 | 
			
		||||
        }
 | 
			
		||||
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
 | 
			
		||||
        String token = JwtUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
 | 
			
		||||
        dbUser.setToken(token);
 | 
			
		||||
        return dbUser;
 | 
			
		||||
    }
 | 
			
		||||
@ -84,7 +84,9 @@ public class UserService {
 | 
			
		||||
 | 
			
		||||
            userMapper.addUser(user);
 | 
			
		||||
            return user;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    public User selectByUsername(String username) {
 | 
			
		||||
        return userMapper.selectByUserName(username);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -3,7 +3,9 @@ package top.suyiiyii.sims.utils;
 | 
			
		||||
import cn.hutool.core.date.DateUtil;
 | 
			
		||||
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 jakarta.annotation.PostConstruct;
 | 
			
		||||
import jakarta.annotation.Resource;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
@ -19,12 +21,12 @@ import java.util.Date;
 | 
			
		||||
 * @Author tortoise
 | 
			
		||||
 * @Date 2024/8/12 11:44
 | 
			
		||||
 * @PackageName:top.suyiiyii.sims.utils
 | 
			
		||||
 * @ClassName: TokenUtils
 | 
			
		||||
 * @ClassName: JwtUtils
 | 
			
		||||
 * @Description: TODO
 | 
			
		||||
 * @Version 1.0
 | 
			
		||||
 */
 | 
			
		||||
@Component
 | 
			
		||||
public class TokenUtils{
 | 
			
		||||
public class JwtUtils {
 | 
			
		||||
    private static UserMapper staticUserMapper;
 | 
			
		||||
    @Resource
 | 
			
		||||
    UserMapper userMapper;
 | 
			
		||||
@ -42,17 +44,17 @@ public class TokenUtils{
 | 
			
		||||
     * @return: java.lang.String
 | 
			
		||||
     */
 | 
			
		||||
    public static String createToken(String userId, String sign) {
 | 
			
		||||
        return JWT.create().withAudience(userId)
 | 
			
		||||
        return JWT.create()
 | 
			
		||||
                .withAudience(userId)
 | 
			
		||||
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))
 | 
			
		||||
                .sign(Algorithm.HMAC256(sign));
 | 
			
		||||
 | 
			
		||||
                // 设置令牌过期时间为2小时
 | 
			
		||||
    }
 | 
			
		||||
    public static User getCurrentUser() {
 | 
			
		||||
        try {
 | 
			
		||||
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
 | 
			
		||||
            String token = request.getHeader("token");
 | 
			
		||||
            if (StrUtil.isBlank(token)) {
 | 
			
		||||
 | 
			
		||||
            if (StrUtil.isNotBlank(token)) {
 | 
			
		||||
                String userId = JWT.decode(token).getAudience().get(0);
 | 
			
		||||
                return staticUserMapper.selectById(Integer.valueOf(userId));
 | 
			
		||||
            }
 | 
			
		||||
@ -61,5 +63,23 @@ public class TokenUtils{
 | 
			
		||||
        }
 | 
			
		||||
        return null;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // 验证 JWT 令牌
 | 
			
		||||
    public static boolean verifyToken(String token, String secret) {
 | 
			
		||||
        try {
 | 
			
		||||
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build(); // 创建 JWT 验证器
 | 
			
		||||
            jwtVerifier.verify(token); // 验证令牌
 | 
			
		||||
            return true;
 | 
			
		||||
        } catch (JWTDecodeException e) {
 | 
			
		||||
            // 处理异常或记录日志
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    public static String extractUserId(String token) {
 | 
			
		||||
        try {
 | 
			
		||||
            return JWT.decode(token).getAudience().get(0); // 从 token 中提取用户ID
 | 
			
		||||
        } catch (JWTDecodeException e) {
 | 
			
		||||
            // 处理异常或记录日志
 | 
			
		||||
            return null;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user