Spring Security using Custom Authentication Provider

Tools and Technologies used
1)Eclipse IDE Mars Release (4.5.0)
2)Java 8
3)Spring framework 4.2.0
4)Spring security 3.2
5)Tomcat 8




Follow steps from the Spring MVC project link to setup a spring maven hello world project.

Project Structure

Then follow below steps to achieve spring security using custom Authentication Provider.

Modify pom.xml as below to have spring security dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>SpringSecurity</groupId>
  5.   <artifactId>SpringSecurityCustomAuthenticationProvider</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringSecurityCustomAuthenticationProvider Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.         <spring-security.version>3.2.7.RELEASE</spring-security.version>
  13.     </properties>
  14.     <dependencies>
  15.         <dependency>
  16.             <groupId>junit</groupId>
  17.             <artifactId>junit</artifactId>
  18.             <version>3.8.1</version>
  19.             <scope>test</scope>
  20.         </dependency>
  21.         <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context,
  22.             spring-web -->
  23.         <dependency>
  24.             <groupId>org.springframework</groupId>
  25.             <artifactId>spring-web</artifactId>
  26.             <version>${org.springframework.version}</version>
  27.         </dependency>
  28.  
  29.         <dependency>
  30.             <groupId>org.springframework</groupId>
  31.             <artifactId>spring-webmvc</artifactId>
  32.             <version>${org.springframework.version}</version>
  33.         </dependency>
  34.        
  35.          <!-- Spring Security Dependencies -->
  36.         <dependency>
  37.             <groupId>org.springframework.security</groupId>
  38.             <artifactId>spring-security-core</artifactId>
  39.             <version>${spring-security.version}</version>
  40.          </dependency>
  41.          <dependency>
  42.             <groupId>org.springframework.security</groupId>
  43.             <artifactId>spring-security-web</artifactId>
  44.             <version>${spring-security.version}</version>
  45.           </dependency>
  46.           <dependency>
  47.             <groupId>org.springframework.security</groupId>
  48.             <artifactId>spring-security-config</artifactId>
  49.             <version>${spring-security.version}</version>
  50.           </dependency>
  51.          
  52.     </dependencies>
  53.     <build>
  54.            <finalName>SpringSecurityCustomAuthenticationProvider</finalName>
  55.         <plugins>
  56.             <plugin>
  57.                 <groupId>org.apache.maven.plugins</groupId>
  58.                 <artifactId>maven-compiler-plugin</artifactId>
  59.                 <version>2.5.1</version>
  60.                 <configuration>
  61.                     <source>1.8</source>
  62.                     <target>1.8</target>
  63.                 </configuration>
  64.             </plugin>
  65.         </plugins>
  66.     </build>
  67.  
  68. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringSecurity</groupId>
  <artifactId>SpringSecurityCustomAuthenticationProvider</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringSecurityCustomAuthenticationProvider Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
		<spring-security.version>3.2.7.RELEASE</spring-security.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, 
			spring-web -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		 <!-- Spring Security Dependencies -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring-security.version}</version>
         </dependency> 
         <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring-security.version}</version>
          </dependency> 
          <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring-security.version}</version>
          </dependency>
          
	</dependencies>
	<build>
		   <finalName>SpringSecurityCustomAuthenticationProvider</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
 
</project>

Modify web.xml to add spring security filter as below

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.   <display-name>Archetype Created Web Application</display-name>
  6.  
  7.   <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.             /WEB-INF/spring-security.xml
  16.         </param-value>
  17.         </init-param>
  18.         <load-on-startup>1</load-on-startup>
  19.     </servlet>
  20.     <servlet-mapping>
  21.         <servlet-name>mvc-dispatcher</servlet-name>
  22.         <url-pattern>/</url-pattern>
  23.     </servlet-mapping>
  24.  
  25.     <listener>
  26.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  27.     </listener>
  28.     <!-- Loads Spring Security configuration file -->
  29.     <context-param>
  30.         <param-name>contextConfigLocation</param-name>
  31.         <param-value>
  32.             /WEB-INF/spring-mvc.xml,
  33.             /WEB-INF/spring-security.xml
  34.         </param-value>
  35.     </context-param>
  36.    
  37.         <!-- Spring Security filter -->
  38.     <filter>
  39.         <filter-name>springSecurityFilterChain</filter-name>
  40.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  41.     </filter>
  42.  
  43.     <filter-mapping>
  44.         <filter-name>springSecurityFilterChain</filter-name>
  45.         <url-pattern>/*</url-pattern>
  46.     </filter-mapping>
  47.    
  48. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

  <display-name>Archetype Created Web Application</display-name>
  
  <!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
			/WEB-INF/spring-security.xml
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- Loads Spring Security configuration file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml,
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>
	
		<!-- Spring Security filter -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

Add spring security config file as below

  1. <beans:beans xmlns="http://www.springframework.org/schema/security"
  2.   xmlns:beans="http://www.springframework.org/schema/beans"
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.   xsi:schemaLocation="http://www.springframework.org/schema/beans
  5.          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  6.          http://www.springframework.org/schema/security
  7.          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
  8.            
  9.     <http auto-config='true'>
  10.       <intercept-url pattern="/secured/*" access="ROLE_USER" />
  11.     </http>
  12.        
  13.     <authentication-manager>
  14.       <authentication-provider ref="customAuthenticationProvider"/>
  15.     </authentication-manager>  
  16.            
  17. </beans:beans>
<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-3.2.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
           
    <http auto-config='true'>
      <intercept-url pattern="/secured/*" access="ROLE_USER" />
    </http>
       
    <authentication-manager>
      <authentication-provider ref="customAuthenticationProvider"/>
    </authentication-manager>   
           
</beans:beans>

Provide Authentication provider reference to our custom class which can handle custom authentication mechanism.
Create controller class as below

  1. package com.kb.controller;
  2.  
  3.  
  4. import org.springframework.security.core.context.SecurityContextHolder;
  5. import org.springframework.security.core.userdetails.User;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.ModelMap;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10.  
  11. import com.kb.model.CustomUser;
  12.  
  13.  
  14. @Controller
  15. public class HomeController {
  16.    
  17.    
  18.     @RequestMapping(value="/helloworld", method = RequestMethod.GET)
  19.     public String helloWorld(ModelMap model) {
  20.     model.addAttribute("message", "Welcome to the Hello World page");
  21.     return "helloworld";
  22.      
  23.     }
  24.    
  25.     @RequestMapping(value="/secured/home", method = RequestMethod.GET)
  26.     public String securedHome(ModelMap model) {
  27.         Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  28.         CustomUser user=null;
  29.         if (principal instanceof CustomUser) {
  30.         user = ((CustomUser)principal);
  31.         }
  32.      
  33.     String name = user.getUsername();
  34.     model.addAttribute("username", name);
  35.     model.addAttribute("message", "Welcome to the secured page");
  36.     return "home";
  37.      
  38.     }
  39.  
  40. }
package com.kb.controller;


import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.model.CustomUser;


@Controller
public class HomeController {
	
	
	@RequestMapping(value="/helloworld", method = RequestMethod.GET)
	public String helloWorld(ModelMap model) {
	model.addAttribute("message", "Welcome to the Hello World page");
	return "helloworld";
	 
	}
	
	@RequestMapping(value="/secured/home", method = RequestMethod.GET)
	public String securedHome(ModelMap model) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		CustomUser user=null;
		if (principal instanceof CustomUser) {
		user = ((CustomUser)principal);
		}
	 
	String name = user.getUsername();
	model.addAttribute("username", name);
	model.addAttribute("message", "Welcome to the secured page");
	return "home";
	 
	}

}

Create a custom authentication provider class as below

  1. package com.kb.authentication.provider;
  2.  
  3. import java.util.Collection;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.security.authentication.AuthenticationProvider;
  7. import org.springframework.security.authentication.BadCredentialsException;
  8. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  9. import org.springframework.security.core.Authentication;
  10. import org.springframework.security.core.AuthenticationException;
  11. import org.springframework.security.core.GrantedAuthority;
  12. import org.springframework.stereotype.Component;
  13.  
  14. import com.kb.model.CustomUser;
  15. import com.kb.service.CustomUserService;
  16.  
  17. @Component
  18. public class CustomAuthenticationProvider implements AuthenticationProvider{
  19.  
  20.     @Autowired
  21.     private CustomUserService userService;
  22.    
  23.     public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  24.           String username = authentication.getName();
  25.           String password = (String) authentication.getCredentials();
  26.      
  27.             CustomUser user = userService.loadUserByUsername(username);
  28.      
  29.             if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
  30.                 throw new BadCredentialsException("Username not found.");
  31.             }
  32.      
  33.             if (!password.equals(user.getPassword())) {
  34.                 throw new BadCredentialsException("Wrong password.");
  35.             }
  36.      
  37.             Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
  38.      
  39.             return new UsernamePasswordAuthenticationToken(user, password, authorities);
  40.     }
  41.  
  42.     public boolean supports(Class<?> arg0) {
  43.         return true;
  44.     }
  45.  
  46. }
package com.kb.authentication.provider;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.kb.model.CustomUser;
import com.kb.service.CustomUserService;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{

	@Autowired
	private CustomUserService userService;
	
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		  String username = authentication.getName();
	      String password = (String) authentication.getCredentials();
	 
	        CustomUser user = userService.loadUserByUsername(username);
	 
	        if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
	            throw new BadCredentialsException("Username not found.");
	        }
	 
	        if (!password.equals(user.getPassword())) {
	            throw new BadCredentialsException("Wrong password.");
	        }
	 
	        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
	 
	        return new UsernamePasswordAuthenticationToken(user, password, authorities);
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}

}

Our custom class implements AuthenticationProvider interface provided by spring security
And authenticate method is overridden with our logic.
We will call service class method to load the user based on user name.
If the user is not found or password mismatch then throw an exception , if he is a valid user return the authentication token which is expected by spring security.

Create a user service class to obtain the user details.

  1. package com.kb.service;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.security.core.userdetails.UserDetailsService;
  5. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import com.kb.dao.UserDAOImpl;
  9. import com.kb.model.CustomUser;
  10.  
  11. @Service
  12. public class CustomUserService implements UserDetailsService {
  13.  
  14.      @Autowired
  15.      private UserDAOImpl userDao;
  16.      
  17.      
  18.     public CustomUser loadUserByUsername(String username) throws UsernameNotFoundException {
  19.         return userDao.loadUserByUsername(username);
  20.     }
  21.  
  22. }
package com.kb.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.kb.dao.UserDAOImpl;
import com.kb.model.CustomUser;

@Service
public class CustomUserService implements UserDetailsService {

	 @Autowired
	 private UserDAOImpl userDao;
	 
	 
	public CustomUser loadUserByUsername(String username) throws UsernameNotFoundException {
		return userDao.loadUserByUsername(username);
	}

}

Service class calls the DAO layer to obtain the user data based on user name

Create the User DAO class which returns the user based on username supplied.

  1. package com.kb.dao;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.springframework.stereotype.Repository;
  7.  
  8. import com.kb.model.CustomUser;
  9. import com.kb.model.Role;
  10.  
  11. @Repository
  12. public class UserDAOImpl {
  13.    
  14.      public CustomUser loadUserByUsername(final String username) {
  15.          //Write your DB call code to get the user details from DB,But I am just hard coding the user
  16.             CustomUser user = new CustomUser();
  17.             user.setFirstName("kb");
  18.             user.setLastName("gc");
  19.             user.setUsername("kb");
  20.             user.setPassword("1234");
  21.             Role r = new Role();
  22.             r.setName("ROLE_USER");
  23.             List<Role> roles = new ArrayList<Role>();
  24.             roles.add(r);
  25.             user.setAuthorities(roles);
  26.             return user;
  27.         }
  28.  
  29. }
package com.kb.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.kb.model.CustomUser;
import com.kb.model.Role;

@Repository
public class UserDAOImpl {
	
	 public CustomUser loadUserByUsername(final String username) {
		 //Write your DB call code to get the user details from DB,But I am just hard coding the user
		 	CustomUser user = new CustomUser();
	        user.setFirstName("kb");
	        user.setLastName("gc");
	        user.setUsername("kb");
	        user.setPassword("1234");
	        Role r = new Role();
	        r.setName("ROLE_USER");
	        List<Role> roles = new ArrayList<Role>();
	        roles.add(r);
	        user.setAuthorities(roles);
	        return user;
	    }

}

Create our own user class as below

  1. package com.kb.model;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.security.core.userdetails.UserDetails;
  6.  
  7. public class CustomUser implements UserDetails {
  8.    
  9.     private String username;
  10.     private String password;
  11.     private String email;
  12.     private String firstName;
  13.     private String lastName;
  14.  
  15.     /* Spring Security related fields*/
  16.     private List<Role> authorities;
  17.     private boolean accountNonExpired = true;
  18.     private boolean accountNonLocked = true;
  19.     private boolean credentialsNonExpired = true;
  20.     private boolean enabled = true;
  21.     public String getUsername() {
  22.         return username;
  23.     }
  24.     public void setUsername(String username) {
  25.         this.username = username;
  26.     }
  27.     public String getPassword() {
  28.         return password;
  29.     }
  30.     public void setPassword(String password) {
  31.         this.password = password;
  32.     }
  33.     public String getEmail() {
  34.         return email;
  35.     }
  36.     public void setEmail(String email) {
  37.         this.email = email;
  38.     }
  39.     public String getFirstName() {
  40.         return firstName;
  41.     }
  42.     public void setFirstName(String firstName) {
  43.         this.firstName = firstName;
  44.     }
  45.     public String getLastName() {
  46.         return lastName;
  47.     }
  48.     public void setLastName(String lastName) {
  49.         this.lastName = lastName;
  50.     }
  51.     public List<Role> getAuthorities() {
  52.         return authorities;
  53.     }
  54.     public void setAuthorities(List<Role> authorities) {
  55.         this.authorities = authorities;
  56.     }
  57.     public boolean isAccountNonExpired() {
  58.         return accountNonExpired;
  59.     }
  60.     public void setAccountNonExpired(boolean accountNonExpired) {
  61.         this.accountNonExpired = accountNonExpired;
  62.     }
  63.     public boolean isAccountNonLocked() {
  64.         return accountNonLocked;
  65.     }
  66.     public void setAccountNonLocked(boolean accountNonLocked) {
  67.         this.accountNonLocked = accountNonLocked;
  68.     }
  69.     public boolean isCredentialsNonExpired() {
  70.         return credentialsNonExpired;
  71.     }
  72.     public void setCredentialsNonExpired(boolean credentialsNonExpired) {
  73.         this.credentialsNonExpired = credentialsNonExpired;
  74.     }
  75.     public boolean isEnabled() {
  76.         return enabled;
  77.     }
  78.     public void setEnabled(boolean enabled) {
  79.         this.enabled = enabled;
  80.     }
  81.  
  82. }
package com.kb.model;

import java.util.List;

import org.springframework.security.core.userdetails.UserDetails;

public class CustomUser implements UserDetails {
	
	private String username;
    private String password;
    private String email;
    private String firstName;
    private String lastName;
 
    /* Spring Security related fields*/
    private List<Role> authorities;
    private boolean accountNonExpired = true;
    private boolean accountNonLocked = true;
    private boolean credentialsNonExpired = true;
    private boolean enabled = true;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public List<Role> getAuthorities() {
		return authorities;
	}
	public void setAuthorities(List<Role> authorities) {
		this.authorities = authorities;
	}
	public boolean isAccountNonExpired() {
		return accountNonExpired;
	}
	public void setAccountNonExpired(boolean accountNonExpired) {
		this.accountNonExpired = accountNonExpired;
	}
	public boolean isAccountNonLocked() {
		return accountNonLocked;
	}
	public void setAccountNonLocked(boolean accountNonLocked) {
		this.accountNonLocked = accountNonLocked;
	}
	public boolean isCredentialsNonExpired() {
		return credentialsNonExpired;
	}
	public void setCredentialsNonExpired(boolean credentialsNonExpired) {
		this.credentialsNonExpired = credentialsNonExpired;
	}
	public boolean isEnabled() {
		return enabled;
	}
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

}

Create a class Role

  1. package com.kb.model;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.security.core.GrantedAuthority;
  6.  
  7. public class Role implements GrantedAuthority{
  8.    
  9.     private String name;
  10.      
  11.  
  12.     public String getName() {
  13.         return name;
  14.     }
  15.  
  16.     public void setName(String name) {
  17.         this.name = name;
  18.     }
  19.  
  20.     public String getAuthority() {
  21.         return this.name;
  22.     }
  23. }
package com.kb.model;

import java.util.List;

import org.springframework.security.core.GrantedAuthority;

public class Role implements GrantedAuthority{
	
	private String name;
	 

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthority() {
		return this.name;
	}
}

Right click on the project and run as Maven install, copy the war file into webapps folder of server and start the server.
Let’s access the public url which is not intercepted by spring security

http://localhost:8080/SpringSecurityCustomAuthenticationProvider/helloworld

Let’s access the secured url which is intercepted by spring security

http://localhost:8080/SpringSecurityCustomAuthenticationProvider/secured/home

Let’s put invalid username and check the output

Let’s put invalid password and check the output

Note : The error messages are coming as we mentioned in our provider class.

Let’s put valid credentials and check the output

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on