Spring MVC - Handling redirection - spring

I want to redirect a page in server side (using spring), but the URL should remain the same.
For ex: if user tries http://www.example.com/page1, I want to render content of http://www.example.com/page2 in browser but the URL should still point to http://www.example.com/page1.
I tried 301, 302, 307 redirects, but all page URLs are changing to http://www.example.com/page2.
Is there anyway to achieve this?

It's a problem of terminology. What you're looking for is forward rather than redirect. If you're interested you may want to look that up e.g. here: http://www.javapractices.com/topic/TopicAction.do?Id=181.
There are at least two ways of doing this:
Traditional, RequestDispatcher can be used outside a Spring WebMVC application, too.
public class MyController extends AbstractController {
#Override
protected void handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
request.getRequestDispatcher("/new/path").forward(request, response);
}
}
Spring WebMVC notation:
public class MyController extends AbstractController {
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
return new ModelAndView("forward:/new/path");
}
}

Related

How to intercept not authorazied request to a rest controller (method level authorization) - Spring Boot

In a REST Controller I have the following method.
#GetMapping("/activate_user")
#RolesAllowed({Role.ROLE_ADMIN})
public void activateUser() {
// Some code here
}
If a user with ROLE_ADMIN calls this method, it works like it should.
If a user without ROLE_ADMIN calls this method, it return an Http-Status 403. That is also ok, but I want now to intercept this call in case the user is not authorized, run some custom code and return some JSON data back to the caller.
I don't know how it could be done with Spring?!
You can override the accessdenied exception and this way it will only be executed for 403 unauthorized.
#Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.getWriter().write("Custom Access Denied Message");
}
you can use MVC Interceptor Configuration to intercept specific URLs/APIs
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/adminRole/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/auth/*", "/ui/**", "/xyz/**");
}
}
You can even exclude specific URL's.

spring mvc: applying #ModelAttribute on non-#Controller endpoints

I've read this suggestion on using #ModelAttribute for injecting parameters to the model globally. Is my understading correct, that such an approach will not cover views rendered by, e.g. <mvc:view-controller>, or a form-login custom login page?
If so, is there a way to extend such a mechanism to include all views?
Thanks
Ended-up using an Interceptor, as laid-out in this reply. Registered interceptor to intercept all non-resource endpoints (using mvc:exclude-mapping).
public class HandlerInterceptor extends HandlerInterceptorAdapter {
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView == null)
return;
modelAndView.addObject("foo", "bar");
}

Spring Boot Redirect to requested URL after login

I have a Spring Boot UI application. I am trying to redirect users to the originally requested URL after login.
When a user requests http://www.example.com/myapp/user/22, the application aptly redirects to http://www.example.com/myapp/login. Once the user logs in, the application redirects to http://www.example.com/myapp/dashboard. I would like the application to redirect to http://www.example.com/myapp/user/22.
I have gone through several links and feel I have a proper configuration, yet, redirection is not working as expected.
My Security Config is
public class SecurityConfig extends WebSecurityConfigurerAdapter {
.....
....
#Autowired
private MyAuthenticationSuccessHandler authenticationSuccessHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/user/**").authenticated()
.and().csrf().disable().formLogin()
.successHandler(authenticationSuccessHandler)
......
and My Success Handler is
#Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
...
public MyAuthenticationSuccessHandler() {
super();
this.setDefaultTargetUrl("/myapp/dashboard");
this.setUseReferer(true);
}
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
//Do something ..........
........
.........
super.onAuthenticationSuccess(request, response, authentication);
}
I tried using SavedRequestAwareAuthenticationSuccessHandler too.
I notice that my success handler is invoked, but the target URL is always /user/login and my login controller is invoked..
#RequestMapping("/login")
public ModelAndView login(#ModelAttribute() {
if(!userIdentified) {
//go to login page
} else {
new ModelAndView("redirect:/myapp/dashboard");
}
}
and the user is redirected to "dashboard".
What else am I missing?
Use "Referer" from session attribute to get the latest request URL. On my app, i use this one
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
public static final String REDIRECT_URL_SESSION_ATTRIBUTE_NAME = "REDIRECT_URL";
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
Object redirectURLObject = request.getSession().getAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
if(redirectURLObject != null)
setDefaultTargetUrl(redirectURLObject.toString());
else{
setDefaultTargetUrl("/");
}
request.getSession().removeAttribute(REDIRECT_URL_SESSION_ATTRIBUTE_NAME);
super.onAuthenticationSuccess(request, response, authentication);
}
}
Edit :
Sorry i forgot to show the login controller
#RequestMapping(method = RequestMethod.GET, value = {"/login"})
String login(Model model, Principal principal, HttpServletRequest request) throws Exception{
String referer = request.getHeader("Referer"); //Get previous URL before call '/login'
//save referer URL to session, for later use on CustomAuthenticationSuccesshandler
request.getSession().setAttribute(CustomAuthenticationSuccessHandler.REDIRECT_URL_SESSION_ATTRIBUTE_NAME, referer);
return principal == null ? "login" : "redirect:/";
}
Although Singgih S answer works, BUT there is a better way as below :
Ref:
https://www.baeldung.com/spring-security-redirect-login
There is no magic in these easy to use features in Spring Security.
When a secured resource is being requested, the request will be
filtered by a chain of various filters. Authentication principals and
permissions will be checked. If the request session is not
authenticated yet, AuthenticationException will be thrown.
The AuthenticationException will be caught in the
ExceptionTranslationFilter, in which an authentication process will be
commenced, resulting in a redirection to the login page.
Therefore :
1. When redirection to the "/login" page occurs, your secured request url is saved in the session as DefaultSavedRequest object.
2. Also we know when a successful form based login occurs, one of the implementations of AuthenticationSuccessHandler is called.
so we can create a custom class and get DefaultSavedRequest in it as below :
public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
if(defaultSavedRequest != null){
getRedirectStrategy().sendRedirect(request, response, defaultSavedRequest.getRedirectUrl());
}else{
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
3. We have to introduce this class in WebSecurityConfigurerAdapter :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.(...).anyRequest().authenticated().and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.successHandler(new CustomAuthenticationSuccessHandler());
So you can implement your logic in the above onAuthenticationSuccess method.
Best wishes
The Spring route, ala extending SavedRequestAwareAuthenticationSuccessHandler or SimpleUrlAuthenticationSuccessHandler can be a bit clunky to implement. In the controller (ex. a POST method that processes logins), you can do the header request yourself; ex:
HttpServletRequest request =null;
String priorUrl = request.getHeader("Referer");
You will notice that you will have the URL prior to either a manual (initiated by user) logout or a session timeout (as handled by Spring session): you'll get an https://iAmPriorUrl.com/.... Then you can do whatever you want with it.

Spring Security: How can I set a RememberMe cookie url path, that differs from the context path?

How in Spring Security can I set a RememberMe cookie url path, that differs from the context path?
Supposing my website's homepage url is (url rewrite):
https://www.mysuperspecialdomain.com
And that my login page has a url like this:
https://www.mysuperspecialdomain.com/shop/account/login
After succesful login the RememberMe cookie has the path /shop (visible in the browser, e.g. Chrome). This is the project's context path.
This leads to the situation, that when I'm going to my homepage, RememberMe is not logging in. Only when I navigate to a url, that starts with https://www.myspecialdomain.com/shop it's doing it.
If you use Spring Security 4.1.0 or higher, you can configure the cookie domain, see RememberMeConfigurer#rememberMeCookieDomain:
The domain name within which the remember me cookie is visible.
but you can't change the context path.
So you have to implement your own RememberMeServices (you could create a sub class of an existing one) and add it with RememberMeConfigurer#rememberMeServices to your security configuration.
I've found a solution to my own question - manipulation of the path of the RememberMe-cookie can be done via an HttpServletResponseWrapper. This is the solution (based on this answer https://stackoverflow.com/a/7047298/7095884):
Define an HttpServletResponseWrapper:
public class RememberMeCookieResponseWrapper extends HttpServletResponseWrapper {
public RememberMeCookieResponseWrapper(HttpServletResponse response) {
super(response);
}
#Override
public void addCookie(Cookie cookie) {
if (cookie.getName().equals("shop")) {
cookie.setPath("/");
}
super.addCookie(cookie);
}
}
Define a filter, that wraps the servlet response with the just defined wrapper:
public class RememberMeCookieFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse) {
HttpServletResponse newResponse =
new RememberMeCookieResponseWrapper((HttpServletResponse)response);
chain.doFilter(request, newResponse);
}
}
}
Add this filter to the Spring Filter Chain in front of the authentication part:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new RememberMeCookieFilter(), UsernamePasswordAuthenticationFilter.class)
...

Set a redirect into a custom Authentication Failure Handler with Spring

Which is the properly way to set a redirect into a custom AuthenticationFailureHandler in Spring?
Is it possible to call a controller?
The code is as follows:
#Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
super.onAuthenticationFailure(request, response, exception);
if (exception.getClass().isAssignableFrom(
CustomUsernameNotFoundException.class)) {
// TODO Set the redirect
}
}
}
Try soemthing like this
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
saveException(request, exception);
//do your things
getRedirectStrategy().sendRedirect(request, response, "/page/login?error=Retry");
}
You are calling super.onAuthenticationFailure which will peform a redirect to the configured URL. The response is thus already committed and you cannot decide to redirect somewhere else.
You can configure SimpleUrlAuthenticationFailureHandler to redirect to one URL and only call the super method if you aren't going to do a redirect yourself.
Alternatively, implement AuthenticationFailureHandler directly and implement all the logic you want in the failure method - once things get beyond a certain level of complexity I prefer to avoid inheritance altogether:
if (oneCondition) {
// redirect to IdP
} else {
// redirect to registration page
}
You can call a controller., a code snippet from you would help, but am getting this from the example that is discussed here.,
Spring Security Tutorial
#RequestMapping(value = "/login/failure")
public String loginFailure() {
String message = "Login Failure!";
return "redirect:/login?message="+message;
}
make sure you understand how the redirect works by looking at the mapping for login in the xml
Spring Mapping.xml
You can redirect to a specific URL.
response.sendRedirect("/redirect");

Resources