[英]How to redirect if user doesn't have the correct Role? Spring Security
我有一个SpringBoot控制器,该控制器返回几个机密信息,并且该信息只能由具有特殊角色的人员访问,对于其他角色,我想重定向到其他控制器。 我正在使用@preAuutorize('hasRole()')
检查用户角色。 请看例子
@PreAuthorize("hasRole('COLOMBIAN_PRESIDENT')")
@GetMapping("/colombia/status")
public ModelAndView showColombiaStatus(){
//This controller can be accessed by colombian president
//for other people, to redirect to showPublicInformation.
}
@GetMapping(value = {"/colombia/public-information"})
public ModelAndView showPublicInformation(){
//for any people
}
如果任何用户不具有COLOMBIAN_PRESIDENT
角色,我想重定向到showPublicInformatio()
如果用户没有名为COLOMBIAN_PRESIDENT
的角色,如何从showColombiaStatus
重定向到showPublicInformation
?
谢谢
我不会采用@ExceptionHandler
方法,而不会采用org.springframework.security.web.access.AccessDeniedHandler
,这是避免将通用异常处理与安全异常混合在一起。
您需要在实现接口AccessDeniedHandler
类中的handle
方法中编写重定向。 在这种方法中,您还可以跟踪所有用户尝试登录系统的内容以及拒绝访问的用户。
您可以在auth
对象下面检查null是否知道访问是否被拒绝。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
您可以创建此处理程序的bean,并在安全配置中进行设置.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
将@ExceptionHandler
添加到您的控制器,例如:
@PreAuthorize("hasRole('COLOMBIAN_PRESIDENT')")
@GetMapping("/colombia/status")
public ModelAndView showColombiaStatus(){
//This controller can be accessed by colombian president
//for other people, to redirect to showPublicInformation.
}
@GetMapping(value = {"/colombia/public-information"})
public ModelAndView showPublicInformation(){
//for any people
}
@ExceptionHandler(AccessDeniedException.class)
public void handleError(HttpServletResponse response){
response.sendRedirect("/colombia/public-information");
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.