feat: 解决JwtUtil解析Token失败问题

解决读取permission的问题
优化Data.sql
添加UserController
This commit is contained in:
yulinling 2025-06-24 22:34:55 +08:00
parent 020e319f78
commit e257e53d69
13 changed files with 80 additions and 44 deletions

View File

@ -1,6 +1,5 @@
package asia.yulinling.workflow.config;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.SchedulingTaskExecutor;

View File

@ -5,11 +5,8 @@ import asia.yulinling.workflow.dto.request.RegisterRequest;
import asia.yulinling.workflow.dto.response.JWTAuthResponse;
import asia.yulinling.workflow.model.ApiResponse;
import asia.yulinling.workflow.service.AuthService;
import asia.yulinling.workflow.utils.ResponseUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -26,7 +23,6 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
@Slf4j
public class AuthController {
private final AuthService authService;

View File

@ -1,12 +1,10 @@
package asia.yulinling.workflow.controller;
import asia.yulinling.workflow.constant.Status;
import asia.yulinling.workflow.dto.request.PageParam;
import asia.yulinling.workflow.dto.response.PageResult;
import asia.yulinling.workflow.exception.JsonException;
import asia.yulinling.workflow.exception.PageException;
import asia.yulinling.workflow.model.ApiResponse;
import asia.yulinling.workflow.dto.response.PageResult;
import asia.yulinling.workflow.model.vo.user.UserVO;
import asia.yulinling.workflow.service.UserService;
import asia.yulinling.workflow.utils.JwtUtil;
import cn.hutool.core.lang.Dict;
@ -14,7 +12,10 @@ import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@ -71,9 +72,4 @@ public class TestController {
PageResult<?> pageResult = new PageResult<>(1, 1, 10, null);
return ApiResponse.ofSuccess(pageResult);
}
@GetMapping("/users")
public ApiResponse<PageResult<UserVO>> usersPage(PageParam pageParam) {
return userService.getUserListByPage(pageParam);
}
}

View File

@ -0,0 +1,37 @@
package asia.yulinling.workflow.controller;
import asia.yulinling.workflow.dto.request.PageParam;
import asia.yulinling.workflow.dto.request.UpdateUserRequest;
import asia.yulinling.workflow.dto.response.PageResult;
import asia.yulinling.workflow.model.ApiResponse;
import asia.yulinling.workflow.model.vo.user.UserVO;
import asia.yulinling.workflow.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 用户控制类
* </p>
*
* @author YLL
* @since 2025/6/24
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Slf4j
public class UserController {
private final UserService userService;
@PostMapping("/update")
public ApiResponse<?> updateUserInfo(@RequestBody UpdateUserRequest updateUserRequest) {
return userService.updateUserInfo(updateUserRequest);
}
@GetMapping("/userList")
public ApiResponse<PageResult<UserVO>> usersPage(PageParam pageParam) {
return userService.getUserListByPage(pageParam);
}
}

View File

@ -1,12 +1,8 @@
package asia.yulinling.workflow.exception.handler;
import asia.yulinling.workflow.exception.BaseException;
import asia.yulinling.workflow.exception.JsonException;
import asia.yulinling.workflow.exception.PageException;
import asia.yulinling.workflow.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

View File

@ -5,6 +5,7 @@ import asia.yulinling.workflow.mapper.RoleMapper;
import asia.yulinling.workflow.model.entity.Permission;
import asia.yulinling.workflow.model.entity.Role;
import asia.yulinling.workflow.model.vo.user.UserPrincipal;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -54,10 +55,11 @@ public class JwtRbacAuthenticationService {
List<Long> roleIds = roles.stream().map(Role::getId).toList();
List<Permission> permissions = permissionMapper.selectPermissionsByRoleId(roleIds);
log.info(permissions.toString());
List<Permission> pagePerms = permissions.stream()
.filter(permission -> Objects.equals(permission.getType(), 1))
.filter(permission -> !permission.getUrl().isEmpty())
.filter(permission -> !permission.getMethod().isEmpty())
.filter(permission -> StrUtil.isNotBlank(permission.getMethod()))
.filter(permission -> StrUtil.isNotBlank(permission.getMethod()))
.toList();
for (Permission permission : pagePerms) {

View File

@ -25,7 +25,7 @@ public interface AuthService {
/**
* 退出登录
*
* @param loginRequest 退出登录请求
* @param request 退出登录请求
* @return 请求结果
*/
ApiResponse<?> logout(HttpServletRequest request) throws SecurityException;

View File

@ -36,6 +36,7 @@ public interface UserService {
/**
* 更改用户角色信息
*
* @return 请求结果
*/
ApiResponse<?> updateUserRole();

View File

@ -10,8 +10,6 @@ import asia.yulinling.workflow.service.AuthService;
import asia.yulinling.workflow.utils.JwtUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -21,7 +19,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.Date;
@ -45,7 +42,7 @@ public class AuthServiceImpl implements AuthService {
/**
* 登录系统
*
*
* @param loginRequest 登录请求
* @return token
*/
@ -62,8 +59,8 @@ public class AuthServiceImpl implements AuthService {
/**
* 退出登录
*
* @param loginRequest 退出登录请求
*
* @param request 退出登录请求
* @return 请求结果
*/
@Override
@ -78,7 +75,7 @@ public class AuthServiceImpl implements AuthService {
/**
* 注册
*
*
* @param request 注册请求
* @return 请求结果
*/

View File

@ -39,19 +39,19 @@ public class JwtUtil {
* jwt 加密 key默认值kw.
*/
@Value("${jwt.config.key}")
private String key = "daf66e01593f61a15b857cf433aae03a005812b31234e149036bcc8dee755dbb";
private final String key = "daf66e01593f61a15b857cf433aae03a005812b31234e149036bcc8dee755dbb";
/**
* jwt 过期时间默认值600000 {@code 10 分钟}.
*/
@Value("${jwt.config.ttl}")
private Long ttl = 600000L;
private final Long ttl = 600000L;
/**
* 开启 记住我 之后 jwt 过期时间默认值 604800000 {@code 7 }
*/
@Value("${jwt.config.remember}")
private Long remember = 604800000L;
private final Long remember = 604800000L;
/**
* 创建JWT
@ -127,10 +127,12 @@ public class JwtUtil {
.parseClaimsJws(token)
.getBody();
String username = claims.getSubject();
Integer userId = (Integer) claims.get("userId");
Object userIdObj = claims.get("userId");
long userId;
userId = userIdObj instanceof Long ? (Long) userIdObj : ((Integer) userIdObj).longValue();
// 2. 获取RedisKey
String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString();
String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId;
// 3. 校验Token是否存在
Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.SECONDS);
@ -155,6 +157,12 @@ public class JwtUtil {
}
}
/**
* 获取userId
*
* @param token token信息
* @return userId
*/
public Long getUserIdByToken(String token) {
Claims claims = parseToken(token);
Object userIdObj = claims.get("userId");
@ -167,6 +175,12 @@ public class JwtUtil {
}
}
/**
* 获取username
*
* @param token token信息
* @return username
*/
public String getUsernameByToken(String token) {
Claims claims = parseToken(token);
return claims.getSubject();
@ -231,10 +245,6 @@ public class JwtUtil {
* @return 返回key
*/
private Key key() {
String secret = this.key;
if (secret == null || secret.isEmpty()) {
throw new IllegalStateException("JWT 签名密钥未配置");
}
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(this.key));
}
}

View File

@ -3,7 +3,6 @@ package asia.yulinling.workflow.utils;
import asia.yulinling.workflow.dto.response.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;

View File

@ -16,7 +16,9 @@ INSERT INTO `wk_permission`
VALUES (1072806379384868864, '在线用户页面-踢出', '/**/api/monitor/online/user/kickout', 2,
'btn:monitor:online:kickout', 'DELETE', 2, 1072806379342925824, NULL, NULL);
INSERT INTO `wk_permission`
VALUES (1072806379384868865, '用户列表', '/users', 1, 'page:test', 'GET', 1, 0, NULL, NULL);
VALUES (1072806379384868865, '用户', '/user/userList', 1, 'page:user:query', 'GET', 1, 0, NULL, NULL);
INSERT INTO `wk_permission`
VALUES (1072806379384868865, '用户', '/user/update', 1, 'page:user:update', 'POST', 1, 0, NULL, NULL);
COMMIT;
BEGIN;
@ -45,6 +47,8 @@ INSERT INTO `wk_role_permission`
VALUES (1072806379238068224, 1072806379313565696);
INSERT INTO `wk_role_permission`
VALUES (1072806379208708096, 1072806379384868865);
INSERT INTO `wk_role_permission`
VALUES (1072806379208708096, 1072806379384868869);
COMMIT;
BEGIN;
@ -80,7 +84,6 @@ VALUES (1072806378780889088,
'2018-12-12 14:52:27', -- update_time
'2018-12-12 14:52:27' -- last_login_time
);
COMMIT;
BEGIN;

View File

@ -11,7 +11,7 @@ CREATE TABLE `wk_user`
`phone` VARCHAR(15) DEFAULT NULL UNIQUE COMMENT '手机号',
`status` INT(2) NOT NULL DEFAULT 1 COMMENT '状态 -1删除 0警用 1启用',
`create_time` DATETIME NOT NULL DEFAULT NOW() COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT NOW() COMMENT '上次更新时间',
`update_time` DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW() COMMENT '上次更新时间',
`last_login_time` DATETIME DEFAULT NULL COMMENT '上次登录时间'
) ENGINE = INNODB
DEFAULT CHARSET = UTF8 COMMENT '用户表';
@ -23,7 +23,7 @@ CREATE TABLE `wk_role`
`name` VARCHAR(32) NOT NULL UNIQUE COMMENT '角色名',
`description` VARCHAR(100) DEFAULT NULL COMMENT '描述',
`create_time` DATETIME NOT NULL DEFAULT NOW() COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT NOW() COMMENT '更新时间'
`update_time` DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW() COMMENT '更新时间'
) ENGINE = INNODB
DEFAULT CHARSET = UTF8 COMMENT '角色表';
@ -39,7 +39,7 @@ CREATE TABLE `wk_permission`
`sort` INT NOT NULL COMMENT '排序',
`parent_id` BIGINT NOT NULL COMMENT '父级ID',
`create_time` DATETIME DEFAULT NOW() COMMENT '创建时间',
`update_time` DATETIME DEFAULT NOW() COMMENT '更新时间',
`update_time` DATETIME DEFAULT NOW() ON UPDATE NOW() COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE INDEX `name` (`name`)
) ENGINE = InnoDB