在Java中實現權限控制可以通過以下步驟來實現:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RequiresPermission {
String[] value();
}
public class PermissionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
RequiresPermission requiresPermission = handlerMethod.getMethodAnnotation(RequiresPermission.class);
if (requiresPermission != null) {
String[] requiredPermissions = requiresPermission.value();
// 檢查用戶是否具有所需權限,如果沒有則返回403
if (!checkPermissions(requiredPermissions, request)) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return false;
}
}
}
return true;
}
private boolean checkPermissions(String[] requiredPermissions, HttpServletRequest request) {
// 檢查用戶是否具有所需權限的邏輯
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PermissionInterceptor());
}
}
@RestController
public class UserController {
@RequiresPermission("user:create")
@PostMapping("/users")
public ResponseEntity createUser() {
// 創建用戶邏輯
return ResponseEntity.ok().build();
}
}
通過以上步驟,可以實現在Java中進行權限控制,確保只有具有所需權限的用戶可以訪問特定的方法或類。