Lesson 1: A Custom Authentication Provider

1. Goals

The goal of this lesson is to guide you through setting up a new, custom authentication provider.


2. Lesson Notes

The relevant module you need to import when you're starting with this lesson is: lssc-module8/m8-lesson1

If you want to skip and see the complete implementation, feel free to jump ahead and import: lssc-module8/m8-lesson2

The credentials used in the code of this lesson are [email protected]/pass (PostConstruct)


2.1. Custom Authentication Provider

By default, the main authentication provider is going to be the DaoAuthenticationProvider.

We're going to now roll our own provider - which simply authenticates against a third-party system. This is going to replace the default provider.

First, let's discuss the contract of the authenticate method in the provider:

  • if authentication succeeds, a full Authentication object (with credentials) is expected as the return
  • if the provider doesn’t support the Authentication input, it will return null (and the next provider will be tried)
  • if the provider does support it and we attempt authentication and fail - AuthenticationException

When we're talking about the exception, it’s important to understand that is the base class for many, many more specific exceptions.

In a production implementation - for a real integration with a third party authentication service - where you’ll have a lot more info to work with. So, we'll need to throw very specific exceptions based on the actual problem that occurred.


Let's now wire in this new custom auth provider with Java config:

@Autowired 
private CustomAuthenticationProvider provider;
...
auth.authenticationProvider(provider);
Now, when we start up the system and check the providers - the parent auth manager is the same but the child manager is now using this new provider as expected.


Also note that - starting with Spring Security 4.1 - you can also define a custom authentication provider without explicitly wiring it in - by just defining it as a new bean.


3. Resources

- The AuthenticationManager, ProviderManager and AuthenticationProvider

- Spring Security Authentication Provider

LSS - A Custom Authentication Provider - transcript.pdf
Complete and Continue