Carlos Mario
Carlos Mario

Reputation: 159

How to redirect if user doesn't have the correct Role? Spring Security

I have a SpringBoot controller and that controller returns several conffidencial information, and that information can be acces only by people with a special role, for other roles i want to redirect to other controller. I'm using @preAuutorize('hasRole()') to check the user roles. Please see the example

@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
}

I want to redirect to showPublicInformatio() if any user doesn't have the role COLOMBIAN_PRESIDENT

How to redirect from showColombiaStatus to showPublicInformation if the user doesn't have the role named COLOMBIAN_PRESIDENT?

Thanks

Upvotes: 0

Views: 1163

Answers (2)

Sabir Khan
Sabir Khan

Reputation: 10132

I wouldn't go by @ExceptionHandler approach but by org.springframework.security.web.access.AccessDeniedHandler , that is avoid mixing generic exception handling with security exceptions.

You need to write your redirection in handle method in class implementing interface AccessDeniedHandler. In this method, you could also trace what all users tried to login to system and what users were denied access.

You can check below auth object for null to know if access is denied.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

You can create a bean of this handler and set in security config like this - .exceptionHandling().accessDeniedHandler(accessDeniedHandler());

Upvotes: 2

Taylor
Taylor

Reputation: 4087

Add an @ExceptionHandler to your controller, e.g.:

@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");
}

Hope this helps.

Upvotes: 1

Related Questions