Spring Security Tutorial: Custom authentication engine

1 11 2014

In this post I showed how to quickly set up and get running a basic security configuration in your Spring application. It uses InMemoryAuthentication – the simpliest possible, rarely used in real life. In Spring Security you can use your own authentication logic. This is how to do it.

Get the source code

Source for this tutorial is available here, under the MyAuthenticationProvider tag: https://github.com/yacekmm/looksok/tree/MyAuthenticationProvider

1. Get the code base

This tutorial is based on code developed in the Spring Security: Securing your MVC app with basic login and password authentication. Follow it first or simply download the source code.

2. Create custom authentication logic class

In this class you can implement whatever you want: verify provided credentials with DB, LDAP, OAuth, File on a filesystem or even read hardcoded credentials. To make things easier for the tutorial I will use the hardcoded hashmap – the goal is to show how to config classes in Spring, not how to access authentication database.

The Authentication class should implement AuthenticationProvider interface and implement its methods: first to indicate whether certain authentication type is supported by this class, and the second one to actually authenticate user. I also added some in memory userRepository with logins, passwords and roles.

This is authentication method:

public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
  User userFromRepository = userRepository.get(authentication.getName().toLowerCase());
  if(userFromRepository != null){
      List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
      grantedAuths.add(new SimpleGrantedAuthority(userFromRepository.role));
      return new UsernamePasswordAuthenticationToken(
      throw new BadCredentialsException("invalid password!");

    //here you can provide even more security checks like 
    //account/password expiration, account lock etc.
    // check AuthenticationException.class siblings
    throw new UsernameNotFoundException("unknown username");

What is happening here is:

  1. check if username exists in repository
  2. check if its password matches
  3. assign roles defined in repository to the authentication object
  4. return authentication token

If any of these steps fails – the AuthenticationException subclass is thrown. The message passed to the exception constructor will be displayed on a login page (only on the Spring default – on your custom login page you need to handle these exceptions)

3. Use MyAuthenticationProvider

To make Spring use your provider you need to have your Autowired method in WebSecurityConfigurerAdapter like that:

public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
  auth.authenticationProvider(new MyAuthenticationProvider());

4. Test it

Go to http://localhost:8080/login and log in with username user or admin (poth with password: pwd). To logout go to page http://localhost:8080/login?logout

Get the source code

Source for this tutorial is available here, under the MyAuthenticationProvider tag: https://github.com/yacekmm/looksok/tree/MyAuthenticationProvider

Did I help you?

I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards




One response

11 11 2014
Spring Security Tutorial: Authorization and user roles | Looks OK!

[…] If you are loking for custom authentication method, take a look at the Spring Security Tutorial: Custom authentication engine. […]

Give Your feedback:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: