Spring MVC role based login example

To allow role based login and redirection we will user custom success handler in spring security.

STEP 1:- Open Eclipse and Create Dynamic Web Project named SpringSecurityRoleBasedLogin 

STEP 2:- Make sure you use Target Runtime as Apache Tomcat 7.0.

STEP 3:- copy below jars to WEB-INF/lib folder.
  • antlr-2.7.6.jar
  • aopalliance-1.0.jar
  • commons-logging-1.2.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.4.Final.jar
  • hibernate-core-4.3.6.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • hibernate-validator-4.3.2.Final.jar
  • javassist-3.12.1.GA.jar
  • jboss-logging-3.1.0.CR1.jar
  • jta.jar
  • jtds.jar
  • persistence-api-1.0.2.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-aspects-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-jdbc-4.1.4.RELEASE.jar
  • spring-orm-4.1.4.RELEASE.jar
  • spring-security-config-4.0.2.RELEASE.jar
  • spring-security-core-4.0.2.RELEASE.jar
  • spring-security-taglibs-4.0.2.RELEASE.jar
  • spring-security-web-4.0.2.RELEASE.jar
  • spring-tx-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4: you can use our Spring Hibernate integration post in order to continue with this. STEP 6 :- Create Custom Success Handler Class.
  • Package: com.tutorialsdesk.security.service
  • Filename: CustomSuccessHandler.java
package com.tutorialsdesk.security.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

 private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
 
 @Override
 protected void handle(HttpServletRequest request, 
 HttpServletResponse response, Authentication authentication) throws IOException {
 String targetUrl = determineTargetUrl(authentication);
 
 if (response.isCommitted()) {
 System.out.println("Can't redirect");
 return;
 }
 
 redirectStrategy.sendRedirect(request, response, targetUrl);
 }
 
 protected String determineTargetUrl(Authentication authentication) {
 String url="";
 
 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
 
 List<String> roles = new ArrayList<String>();
 
 for (GrantedAuthority a : authorities) {
 roles.add(a.getAuthority());
 }
 
 if (isDba(roles)) {
 url = "/api";
 } else if (isAdmin(roles)) {
 url = "/admin";
 } else if (isUser(roles)) {
 url = "/home";
 } else {
 url="/Access_Denied";
 }
 
 return url;
 }
 
 public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
 this.redirectStrategy = redirectStrategy;
 }
 protected RedirectStrategy getRedirectStrategy() {
 return redirectStrategy;
 }
 
 private boolean isUser(List<String> roles) {
 if (roles.contains("ROLE_USER")) {
 return true;
 }
 return false;
 }
 
 private boolean isAdmin(List<String> roles) {
 if (roles.contains("ROLE_ADMIN")) {
 return true;
 }
 return false;
 }
 
 private boolean isDba(List<String> roles) {
 if (roles.contains("ROLE_API")) {
 return true;
 }
 return false;
 }
}
STEP 5 :- Modify spring-security.xml to use customSuccessHandler.
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/security 
 http://www.springframework.org/schema/security/spring-security.xsd">
 
 <http auto-config="true" >
 
 <intercept-url pattern="/" access="permitAll" />
 
 <intercept-url pattern="/home" access="permitAll" />
 
 <intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
 
 <!-- <intercept-url pattern="/api**" access="hasRole('ADMIN') and hasRole('API')" /> -->
 
 <intercept-url pattern="/api**" access="hasRole('ADMIN') or hasRole('API')" />
 
 <!-- access denied page -->
 <access-denied-handler error-page="/Access_Denied" />
 
 <form-login 
 login-processing-url="/login"
 login-page="/login" 
 username-parameter="username"
 password-parameter="password"
 authentication-success-handler-ref="customSuccessHandler"
 authentication-failure-url="/login?error"/>
 <!-- enable csrf protection -->
 <csrf/>
 
 </http>
 
 <!-- Select users and user_roles from database -->
 <authentication-manager >
 <authentication-provider user-service-ref="customUserDetailsService"/>
 </authentication-manager>
 
 <beans:bean id="customUserDetailsService" class="com.tutorialsdesk.security.service.CustomUserDetailsService" />
 <beans:bean id="customSuccessHandler" class="com.tutorialsdesk.security.service.CustomSuccessHandler" />
 
</beans:beans>

STEP 6 :- Run your project enter below URL in your browser

http://localhost:8080/SpringSecurityRoleBasedLogin/

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC role based login Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.
SHARE
    Blogger Comment
    Facebook Comment