Sometimes its required to redirect user to different pages post login
based on the role of the user.For example if an user has an USER
role then we want him to be redirected to /user
and similarly to /admin
for users having ADMIN
role.In this post, we will be discussing about how to redirect user to different pages post login
based on the role of the user.We will be implementing AuthenticationSuccessHandler
of spring boot security
to implement our custom way of redirecting user to different pages after successful login. As usual you can download the complete source code of the project at the end of the article.
Environment Setup
1. JDK 8 2. Spring Boot 3. Intellij Idea/ eclipse 4. MavenMaven Dependencies
There is no any extra maven dependency is required for this case that we used in our previous post of Spring Boot Security Login Example.Hence let us ignore it for while.
Server Side
Now let us define our main configuration for spring security - SpringSecurityConfig.java.class is annotated with @EnableWebSecurity
to enable Spring Security web security support.Here we have injected our SimpleAuthenticationSuccessHandler
class which will be executed once user is successfully authenticated. In the mean time, we have also made configuration to secure our authentication process with CSRF
attack.
package com.developerstack.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private SimpleAuthenticationSuccessHandler successHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login")).and().authorizeRequests() .antMatchers("/user").hasRole("USER") .antMatchers("/admin").hasRole("ADMIN") .and().formLogin().successHandler(/successHandler) .loginPage("/login").and().logout().permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN"); } }
Other Interesting Posts Spring 5 Features and Enhancements Spring Security Password Encoding using Bcrypt Encoder Spring Security Hibernate Example with complete JavaConfig Securing REST API with Spring Security Basic Authentication Spring JMS Activemq Integration with Spring Boot Websocket spring Boot Integration without STOMP with complete JavaConfig Maintaining Spring Session during Websocket Connection Spring MVC Angularjs Integration with complete JavaConfig Spring Hibernate Integration with complete JavaConfig Spring Junit Integration with complete JavaConfig Spring Ehcache Cacheable Example with complete javaConfig Spring Boot Spring MVC Example Spring Boot Thymeleaf Example
Defining Authentication Success handler
Now let us define our AuthenticationSuccessHandler
which will determine the roles assigned to the user and accordingly redirect user different urls. Implementations can do whatever they want but typical behaviour would be to control the navigation to the subsequent destination (using a redirect or a forward).
package com.developerstack.config; import java.io.IOException; import java.util.Collection; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; @Component public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override public void onAuthenticationSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication authentication) throws IOException, ServletException { Collection extends GrantedAuthority> authorities = authentication.getAuthorities(); authorities.forEach(authority -> { if(authority.getAuthority().equals("ROLE_USER")) { try { redirectStrategy.sendRedirect(arg0, arg1, "/user"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if(authority.getAuthority().equals("ROLE_ADMIN")) { try { redirectStrategy.sendRedirect(arg0, arg1, "/admin"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { throw new IllegalStateException(); } }); } }
Here is the controller mapping for different Http request for /user and /admin.
DashboardController.javapackage com.developerstack.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class DashboardController { @RequestMapping(value = "/admin", method = RequestMethod.GET) public ModelAndView admin() { ModelAndView model = new ModelAndView(); model.setViewName("admin"); return model; } @RequestMapping(value = "/user", method = RequestMethod.GET) public ModelAndView user() { ModelAndView model = new ModelAndView(); model.setViewName("user"); return model; } }
Run Application
1. Run Application.java
as a java application.
2. Hit the url as http://localhost:8080/login
and following page will be served by the server.
3. Enter username/password as user/password
and user will be redirected to http://localhost:8080/user
4. Again if we enter the username/password as admin/password
, user will be redirected to http://localhost:8080/admin
Conclusion
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.