feat(auth): 将权限信息使用注解的形式固定在接口上

This commit is contained in:
suyiiyii 2024-08-24 20:01:19 +08:00
parent 7724eb43c3
commit 106ee2be90
6 changed files with 49 additions and 27 deletions

View File

@ -14,4 +14,5 @@ import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthAccess {
String[] allowRoles() default {};
}

View File

@ -31,8 +31,6 @@ public class InterceptorConfig extends WebMvcConfigurationSupport {
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/user/login") // 排除不需要验证的路径
.excludePathPatterns("/user/register")
.excludePathPatterns("/v3/api-docs/**");
// 注册AdminInterceptor只拦截以admin/开头的路径

View File

@ -12,6 +12,8 @@ import top.suyiiyii.sims.exception.ServiceException;
import top.suyiiyii.sims.mapper.MpUserMapper;
import top.suyiiyii.sims.utils.JwtUtils;
import java.util.List;
/**
* @Author tortoise
* @Date 2024/8/12 11:33
@ -26,8 +28,12 @@ public class JwtInterceptor implements HandlerInterceptor {
@Autowired
MpUserMapper userMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if ("/error".equals(request.getRequestURI())) {
return true;
}
// Authorization 头中获取 token
String token = request.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
@ -37,34 +43,40 @@ public class JwtInterceptor implements HandlerInterceptor {
// 如果 Authorization 头中没有 token则尝试从请求参数中获取
token = request.getParameter("token");
}
List<String> allowRoles = null;
// 如果不是映射到方法直接通过
if (handler instanceof HandlerMethod) {
AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
if (annotation != null) {
allowRoles = List.of(annotation.allowRoles());
}
}
// // 执行认证
// if (StrUtil.isBlank(token)) {
// //权限错误
// throw new ServiceException("401", "请登录");
// }
// // 获取 token 中的 user id
// String userId = JwtUtils.extractUserId(token);
// if (userId == null) {
// throw new ServiceException("401", "请登录");
// }
//
// User user = userMapper.selectById(Integer.parseInt(userId));
// if (user == null) {
// throw new ServiceException("401", "请登录");
// }
// // 验证 token 的有效性
// if (!JwtUtils.verifyToken(token, user.getPassword())) {
// throw new ServiceException("401", "请登录");
// }
// 验证token后如果一切正常将token存储到request的属性中
request.setAttribute("token", token);
if (allowRoles != null && !allowRoles.isEmpty()) {
if (allowRoles.contains("guest")) {
return true;
}
}
// 执行认证
if (StrUtil.isBlank(token)) {
//权限错误
throw new ServiceException("401", "请登录");
}
// 获取 token 中的 user id
String userId= JwtUtils.extractUserId(token);
if (userId == null) {
throw new ServiceException("401", "请登录");
}
User user = userMapper.selectById(Integer.parseInt(userId));
if (user == null) {
throw new ServiceException("401", "请登录");
}
// 验证 token 的有效性
if (!JwtUtils.verifyToken(token, user.getPassword())) {
throw new ServiceException("401", "请登录");
}
// 验证token后如果一切正常将token存储到request的属性中
request.setAttribute("token", token);
return true;
throw new ServiceException("403", "权限不足");
}
}

View File

@ -5,14 +5,17 @@ import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import top.suyiiyii.sims.common.AuthAccess;
@RestController
public class HealthzController {
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/healthz")
public String healthz() {
return "ok";
}
@AuthAccess(allowRoles = {"guest"})
@PostMapping("/healthz")
public HealthzResponse healthzPost() {
return new HealthzResponse("health");

View File

@ -3,6 +3,7 @@ package top.suyiiyii.sims.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import top.suyiiyii.sims.common.AuthAccess;
import top.suyiiyii.sims.common.Result;
import java.util.List;
@ -10,15 +11,20 @@ import java.util.List;
@RestController
public class HelloController {
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/hello")
public String hello(String username) {
return "Hello " + username;
}
@AuthAccess(allowRoles = {"guest"})
@PostMapping("/hello")
public List<String> helloPost(String username , Integer age) {
List<String> list = List.of(username,age.toString());
public List<String> helloPost(String username, Integer age) {
List<String> list = List.of(username, age.toString());
return list;
}
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/helloResult")
public Result healthz() {
return Result.success("Hello World");

View File

@ -38,7 +38,7 @@ public class UserController {
RoleService roleService;
@AuthAccess
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/")
public Result hello() {
@ -46,6 +46,7 @@ public class UserController {
}
@AuthAccess(allowRoles = {"guest"})
@PostMapping("/user/login")
public Result<LoginResponse> login(@RequestBody LoginRequest request, HttpServletRequest httpServletRequest) {
log.info("login request:{}", request);
@ -63,6 +64,7 @@ public class UserController {
return Result.success(response);
}
@AuthAccess(allowRoles = {"guest"})
@PostMapping("/user/register")
public Result<CommonResponse> register(@RequestBody RegisterRequest request) {
log.info("register request:{}", request);