【发布时间】:2018-03-31 02:23:03
【问题描述】:
我有一个这样的自定义注释:
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@PreAuthorize(AllowedForSystemUsers.condition)
public @interface AllowedForSystemUsers {
String condition = "hasAnyRole({'ROLE_ADMIN', 'ROLE_USER'})";
}
我将注释放在我的Controller 方法中,如下所示:
@RequestMapping(value="/search", method=RequestMethod.POST)
@AllowedForSystemUsers
public String searchRooms(@ModelAttribute Booking booking, Model model, long type) {
//do something
}
我的ExceptionHandler 是这样的:
@ExceptionHandler(value = AccessDeniedException.class)
public ModelAndView accessDenied(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {
return new ModelAndView("redirect:/error");
}
所以当用户没有ROLE_ADMIN 或ROLE_USER 的身份验证时,会发生AccessDeniedException 并且代码会运行到accessDenied() 方法中。
我的问题是我怎么知道@AllowedForSystemUsers 注释是否触发了这个AccessDeniedException?因为其他代码也可能触发AccessDeniedException
谢谢!
【问题讨论】:
-
你需要在控制器中抛出你的异常。要执行全局异常处理程序,您需要从其他地方抛出异常。
-
你可以考虑创建
AccessDeniedException的子类并在@AllowedForSystemUsers处理时抛出它 -
@SungJinSteveYoo 例如?
-
@AtaurRahmanMunna 所以你的意思是我不能使用 Spring Security 默认
AccessDeniedException? -
为什么不用内置的@PreAuthorize,见docs.spring.io/spring-security/site/docs/current/reference/html/…
标签: java spring spring-boot spring-security