mirror of
https://github.com/suyiiyii/SIMS.git
synced 2025-06-05 13:36:12 +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: 拉取远程仓库的最新代码并合并到当前分支
|
5. git fetch origin && git merge origin/main: 拉取远程仓库的最新代码并合并到当前分支
|
||||||
6. git push origin xxx: 推送当前分支到远程仓库
|
6. git push origin xxx: 推送当前分支到远程仓库
|
||||||
7. 提 PR
|
7. 提 PR
|
||||||
8. require review: 请求review
|
8. require review: 请求reviewpush
|
||||||
9. merge: 合并 PR
|
9. merge: 合并 PR
|
||||||
10. delete: 删除分支
|
10. delete: 删除分支
|
||||||
|
|
||||||
|
@ -1,10 +1,6 @@
|
|||||||
package top.suyiiyii.sims.common;
|
package top.suyiiyii.sims.common;
|
||||||
|
|
||||||
import cn.hutool.core.util.StrUtil;
|
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.annotation.Resource;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
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.entity.User;
|
||||||
import top.suyiiyii.sims.exception.ServiceException;
|
import top.suyiiyii.sims.exception.ServiceException;
|
||||||
import top.suyiiyii.sims.mapper.UserMapper;
|
import top.suyiiyii.sims.mapper.UserMapper;
|
||||||
|
import top.suyiiyii.sims.utils.JwtUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @Author tortoise
|
* @Author tortoise
|
||||||
@ -32,12 +29,12 @@ public class JwtInterceptor implements HandlerInterceptor {
|
|||||||
// 从 Authorization 头中获取 token
|
// 从 Authorization 头中获取 token
|
||||||
String token = request.getHeader("Authorization");
|
String token = request.getHeader("Authorization");
|
||||||
if (token != null && token.startsWith("Bearer ")) {
|
if (token != null && token.startsWith("Bearer ")) {
|
||||||
token = token.substring(7); // 去除 "Bearer " 前缀
|
token = token.substring(7);
|
||||||
|
// 去除 "Bearer " 前缀
|
||||||
} else {
|
} else {
|
||||||
// 如果 Authorization 头中没有 token,则尝试从请求参数中获取
|
// 如果 Authorization 头中没有 token,则尝试从请求参数中获取
|
||||||
token = request.getParameter("token");
|
token = request.getParameter("token");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果不是映射到方法直接通过
|
// 如果不是映射到方法直接通过
|
||||||
if (handler instanceof HandlerMethod) {
|
if (handler instanceof HandlerMethod) {
|
||||||
AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
|
AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
|
||||||
@ -45,17 +42,14 @@ public class JwtInterceptor implements HandlerInterceptor {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 执行认证
|
// 执行认证
|
||||||
if (StrUtil.isBlank(token)) {
|
if (StrUtil.isBlank(token)) {
|
||||||
throw new ServiceException("401", "请登录");//权限错误
|
//权限错误
|
||||||
|
throw new ServiceException("401", "请登录");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取 token 中的 user id
|
// 获取 token 中的 user id
|
||||||
String userId;
|
String userId= JwtUtils.extractUserId(token);
|
||||||
try {
|
if (userId == null) {
|
||||||
userId = JWT.decode(token).getAudience().get(0);
|
|
||||||
} catch (JWTDecodeException j) {
|
|
||||||
throw new ServiceException("401", "请登录");
|
throw new ServiceException("401", "请登录");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,12 +57,8 @@ public class JwtInterceptor implements HandlerInterceptor {
|
|||||||
if (user == null) {
|
if (user == null) {
|
||||||
throw new ServiceException("401", "请登录");
|
throw new ServiceException("401", "请登录");
|
||||||
}
|
}
|
||||||
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();//加密,认证
|
// 验证 token 的有效性
|
||||||
//jwtVerifier 验证器
|
if (!JwtUtils.verifyToken(token, user.getPassword())) {
|
||||||
try {
|
|
||||||
jwtVerifier.verify(token);
|
|
||||||
} catch (JWTDecodeException e) {
|
|
||||||
|
|
||||||
throw new ServiceException("401", "请登录");
|
throw new ServiceException("401", "请登录");
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
@ -73,6 +73,24 @@ public class UserController {
|
|||||||
userService.addUser(user);
|
userService.addUser(user);
|
||||||
|
|
||||||
return Result.success();
|
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查询用户信息
|
* 根据ID查询用户信息
|
||||||
* @param userId 用户ID
|
* @param id 用户ID
|
||||||
* @return 用户对象
|
* @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);
|
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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import top.suyiiyii.sims.common.Result;
|
||||||
import top.suyiiyii.sims.entity.User;
|
import top.suyiiyii.sims.entity.User;
|
||||||
import top.suyiiyii.sims.exception.ServiceException;
|
import top.suyiiyii.sims.exception.ServiceException;
|
||||||
import top.suyiiyii.sims.mapper.UserMapper;
|
import top.suyiiyii.sims.mapper.UserMapper;
|
||||||
import top.suyiiyii.sims.utils.TokenUtils;
|
import top.suyiiyii.sims.utils.JwtUtils;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@ -30,8 +30,8 @@ public class UserService {
|
|||||||
userMapper.addUser(user);
|
userMapper.addUser(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public User selectByUserId(int id) {
|
public User selectById(int id) {
|
||||||
return userMapper.selectByUserId(id);
|
return userMapper.selectById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateUser(User user) {
|
public void updateUser(User user) {
|
||||||
@ -54,7 +54,7 @@ public class UserService {
|
|||||||
if (!dbUser.getPassword().equals(user.getPassword())) {
|
if (!dbUser.getPassword().equals(user.getPassword())) {
|
||||||
throw new ServiceException("密码或用户名错误");
|
throw new ServiceException("密码或用户名错误");
|
||||||
}
|
}
|
||||||
String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
|
String token = JwtUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
|
||||||
dbUser.setToken(token);
|
dbUser.setToken(token);
|
||||||
return dbUser;
|
return dbUser;
|
||||||
}
|
}
|
||||||
@ -84,7 +84,9 @@ public class UserService {
|
|||||||
|
|
||||||
userMapper.addUser(user);
|
userMapper.addUser(user);
|
||||||
return 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.date.DateUtil;
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.auth0.jwt.JWT;
|
import com.auth0.jwt.JWT;
|
||||||
|
import com.auth0.jwt.JWTVerifier;
|
||||||
import com.auth0.jwt.algorithms.Algorithm;
|
import com.auth0.jwt.algorithms.Algorithm;
|
||||||
|
import com.auth0.jwt.exceptions.JWTDecodeException;
|
||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import jakarta.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
@ -19,12 +21,12 @@ import java.util.Date;
|
|||||||
* @Author tortoise
|
* @Author tortoise
|
||||||
* @Date 2024/8/12 11:44
|
* @Date 2024/8/12 11:44
|
||||||
* @PackageName:top.suyiiyii.sims.utils
|
* @PackageName:top.suyiiyii.sims.utils
|
||||||
* @ClassName: TokenUtils
|
* @ClassName: JwtUtils
|
||||||
* @Description: TODO
|
* @Description: TODO
|
||||||
* @Version 1.0
|
* @Version 1.0
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
public class TokenUtils{
|
public class JwtUtils {
|
||||||
private static UserMapper staticUserMapper;
|
private static UserMapper staticUserMapper;
|
||||||
@Resource
|
@Resource
|
||||||
UserMapper userMapper;
|
UserMapper userMapper;
|
||||||
@ -42,17 +44,17 @@ public class TokenUtils{
|
|||||||
* @return: java.lang.String
|
* @return: java.lang.String
|
||||||
*/
|
*/
|
||||||
public static String createToken(String userId, String sign) {
|
public static String createToken(String userId, String sign) {
|
||||||
return JWT.create().withAudience(userId)
|
return JWT.create()
|
||||||
|
.withAudience(userId)
|
||||||
.withExpiresAt(DateUtil.offsetHour(new Date(), 2))
|
.withExpiresAt(DateUtil.offsetHour(new Date(), 2))
|
||||||
.sign(Algorithm.HMAC256(sign));
|
.sign(Algorithm.HMAC256(sign));
|
||||||
|
// 设置令牌过期时间为2小时
|
||||||
}
|
}
|
||||||
public static User getCurrentUser() {
|
public static User getCurrentUser() {
|
||||||
try {
|
try {
|
||||||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||||
String token = request.getHeader("token");
|
String token = request.getHeader("token");
|
||||||
if (StrUtil.isBlank(token)) {
|
if (StrUtil.isNotBlank(token)) {
|
||||||
|
|
||||||
String userId = JWT.decode(token).getAudience().get(0);
|
String userId = JWT.decode(token).getAudience().get(0);
|
||||||
return staticUserMapper.selectById(Integer.valueOf(userId));
|
return staticUserMapper.selectById(Integer.valueOf(userId));
|
||||||
}
|
}
|
||||||
@ -61,5 +63,23 @@ public class TokenUtils{
|
|||||||
}
|
}
|
||||||
return null;
|
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