import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
@GetMapping("/example")
@CheckPermission(module = "example", permission = "read")
public String exampleMethod() {
return "You have read permission on the example module.";
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckPermission {
String module();
String permission();
}
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PermissionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
CheckPermission checkPermission = handlerMethod.getMethodAnnotation(CheckPermission.class);
if (checkPermission != null) {
// 实现权限检查的逻辑
// 例如,检查当前用户是否有权限读取指定模块
// 返回true如果权限被授予,否则返回false
boolean hasPermission = checkUserPermission(checkPermission.module(), checkPermission.permission());
if (!hasPermission) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return false;
}
}
}
return true;
}
private boolean checkUserPermission(String module, String permission) {
// 实现权限检查的逻辑
// 返回true如果用户有权限,否则返回false
return false; // 示例返回值,实际应用中应该查询权限系统
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private PermissionInterceptor permissionInterceptor;
@Ov
评论已关闭