在Java中,您可以创建一个自定义注解,例如@RequiresAuthentication,并将其应用于需要进行身份验证的路由方法上。然后,您可以使用AOP(面向切面编程)来拦截这些方法并在方法执行之前检查用户是否已经通过身份验证。
以下是一个示例代码片段:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresAuthentication {
String[] roles() default {};
}
@Aspect
@Component
public class AuthenticationAspect {
@Autowired
private AuthenticationService authService;
@Autowired
private HttpServletResponse response;
@Around("@annotation(com.example.RequiresAuthentication)")
public Object authenticate(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
RequiresAuthentication annotation = method.getAnnotation(RequiresAuthentication.class);
String[] roles = annotation.roles();
if (!authService.isAuthenticated()) {
if (isAjaxRequest()) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return null;
} else {
response.sendRedirect("/login");
return null;
}
} else if (roles.length > 0 && !authService.hasRoles(roles)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
return joinPoint.proceed();
}
private boolean isAjaxRequest() {
String requestedWithHeader = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equals(requestedWithHeader);
}
}
@RestController
public class MyController {
@GetMapping("/my/route")
@RequiresAuthentication(roles = {"admin"})
public String myRoute() {
return "Hello World!";
}
}
在这个示例中,我们添加了一个名为`roles`的参数,它是一个字符串数组,用于指定需要进行身份验证的用户角色。然后,我们在`AuthenticationAspect`中检查用户是否具有所需的角色。如果用户未通过身份验证,则返回401错误;如果用户没有所需的角色,则返回403错误。