Spring Security Custom Authentication

 

In this example, we will see how to create a custom authentication provider to handle user authentication, by using a simple implementation of UserDetailsService interface.

 

1. Technologies used

  • Spring Security 3.2.5.RELEASE
  • JSF 2.2.8
  • MySQL 5
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

We create a JSF 2 web application.

SpringSecurityCustomAuthentication

 

3. Project dependencies

 

4. Authentication Implementation

We first create an implementation of GrantedAuthority interface to represents an authority granted to an authenticated user.

GrantedAuthorityImpl

 

Then, we create an implementation of UserDetails interface to store user information : username, password and authorities.

UserDetailsImpl

 

And finally, we create an implementation of UserDetailsService interface to load user data based on the username.

We will use a static repository to store users.

UserDetailsServiceImpl

 

When the user is not found or has no GrantedAuthority, a UsernameNotFoundException will be thrown.

 

5. Spring Security configuration

File : spring-security.xml :

 

We tell Spring Security to use our implementation class as user authentication provider.

 

6. Test It

URL : http://localhost:8080/SpringSecurityCustomAuthentication/login.jsf

SpringSecurityCustomAuthentication1

 

Bad authentication :

SpringSecurityCustomAuthentication2

 

Good authentication :

SpringSecurityCustomAuthentication3

 

Download source code

 

Related Posts

  • mahesh

    I need concurrency control(max-seesion=1) and logged in users list(by SessionRegistryImpl) in this application..Please respond quickly.

    • Walid RAHALI

      Add session-management tag in spring-security.xml :

      ….

      and the following listener in web.xml :

      org.springframework.security.web.session.HttpSessionEventPublisher