Reputation: 361
I hope you could give me a hand with the following:
I am using spring security and spring MVC to build a web app, and I need to redirect the flow to the login page, once there is a try to access a forbidden resource (403 HTTP status code).
Now, spring Security already does the work of preventing from unauthorized access to every resource I've exposed in my Restful API (@RestController), and responding with the proper 403 default page. But as I need to redirect to the login page, I need to push spring security to do a redirect instead of sending a 403. In this regard I've been trying to do the following but I haven't been able to make it works:
Setting the HttpSecurity bean to manage the exception when accessing a denied page:
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().exceptionHandling().accessDeniedPage("/security/403"); }
Now, I set my controller to catch /security/403 URL
// for 403 access denied page @RequestMapping(value = "/security/403", method = RequestMethod.GET) public void accesssDenied() { //Do stuff here, redirecting or whatever. }
thanks
Upvotes: 0
Views: 961
Reputation: 1636
Create a new class that acts as an Interceptor.
This class will implement the HandlerInterceptor interface and override the following methods:
From the documentation:
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
– Intercept the execution of a handler (called just before the controller).postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
– called immediately after the controllerafterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler)
– called just before sending response to viewIn your case, use the preHandle()
method to check if the client is trying to access a forbidden resource and if so, redirect the client to the login page. In fact, this is one of the most common paradigms where an Interceptor is used to handle the flow of execution.
Upvotes: 2