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) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
public @interface AuthAccess { public @interface AuthAccess {
String[] allowRoles() default {};
} }

View File

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

View File

@ -12,6 +12,8 @@ import top.suyiiyii.sims.exception.ServiceException;
import top.suyiiyii.sims.mapper.MpUserMapper; import top.suyiiyii.sims.mapper.MpUserMapper;
import top.suyiiyii.sims.utils.JwtUtils; import top.suyiiyii.sims.utils.JwtUtils;
import java.util.List;
/** /**
* @Author tortoise * @Author tortoise
* @Date 2024/8/12 11:33 * @Date 2024/8/12 11:33
@ -26,8 +28,12 @@ public class JwtInterceptor implements HandlerInterceptor {
@Autowired @Autowired
MpUserMapper userMapper; MpUserMapper userMapper;
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if ("/error".equals(request.getRequestURI())) {
return true;
}
// 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 ")) {
@ -37,34 +43,40 @@ public class JwtInterceptor implements HandlerInterceptor {
// 如果 Authorization 头中没有 token则尝试从请求参数中获取 // 如果 Authorization 头中没有 token则尝试从请求参数中获取
token = request.getParameter("token"); token = request.getParameter("token");
} }
List<String> allowRoles = null;
// 如果不是映射到方法直接通过 // 如果不是映射到方法直接通过
if (handler instanceof HandlerMethod) { if (handler instanceof HandlerMethod) {
AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class); AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
if (annotation != null) { 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; return true;
} }
} }
// 执行认证 throw new ServiceException("403", "权限不足");
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;
} }
} }

View File

@ -5,14 +5,17 @@ import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import top.suyiiyii.sims.common.AuthAccess;
@RestController @RestController
public class HealthzController { public class HealthzController {
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/healthz") @GetMapping("/healthz")
public String healthz() { public String healthz() {
return "ok"; return "ok";
} }
@AuthAccess(allowRoles = {"guest"})
@PostMapping("/healthz") @PostMapping("/healthz")
public HealthzResponse healthzPost() { public HealthzResponse healthzPost() {
return new HealthzResponse("health"); 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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import top.suyiiyii.sims.common.AuthAccess;
import top.suyiiyii.sims.common.Result; import top.suyiiyii.sims.common.Result;
import java.util.List; import java.util.List;
@ -10,15 +11,20 @@ import java.util.List;
@RestController @RestController
public class HelloController { public class HelloController {
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/hello") @GetMapping("/hello")
public String hello(String username) { public String hello(String username) {
return "Hello " + username; return "Hello " + username;
} }
@AuthAccess(allowRoles = {"guest"})
@PostMapping("/hello") @PostMapping("/hello")
public List<String> helloPost(String username , Integer age) { public List<String> helloPost(String username, Integer age) {
List<String> list = List.of(username,age.toString()); List<String> list = List.of(username, age.toString());
return list; return list;
} }
@AuthAccess(allowRoles = {"guest"})
@GetMapping("/helloResult") @GetMapping("/helloResult")
public Result healthz() { public Result healthz() {
return Result.success("Hello World"); return Result.success("Hello World");

View File

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