The new Certification Class of Learn Spring Security is out:


1. Overview

This tutorial will show how to set up an Authentication Provider in Spring Security to allow for additional flexibility compared to the standard scenario using a simple UserDetailsService.

2. The Authentication Provider

Spring Security provides a variety of options for performing authentication – all following a simple contract – an Authentication request is processed by an AuthenticationProvider and a fully authenticated object with full credentials is returned.

The standard and most common implementation is the DaoAuthenticationProvider – which retrieves the user details from a simple, read-only user DAO – the UserDetailsService. This User Details Service only has access to the username in order to retrieve the full user entity – and in a large number of scenarios, this is enough.

More custom scenarios will still need to access the full Authentication request to be able to perform the authentication process – for example when authenticating against some external, third party service (such as Crowd) – both the username and the password from the authentication request will be necessary.

For these, more advanced scenarios, we’ll need to define a custom Authentication Provider:

public class CustomAuthenticationProvider
  implements AuthenticationProvider {

    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        if (shouldAuthenticateAgainstThirdPartySystem()) {
            // use the credentials
            // and authenticate against the third-party system
            return new UsernamePasswordAuthenticationToken(
              name, password, new ArrayList<>());
        } else {
            return null;

    public boolean supports(Class<?> authentication) {
        return authentication.equals(

Notice that the granted authorities set on the returned Authentication object are empty – this is because authorities are of course application specific.

3. Register the Auth Provider

Now that the Authentication Provider is defined, we need to specify it in the XML Security Configuration, using the available namespace support:

<?xml version="1.0" encoding="UTF-8"?>

    <http use-expressions="true">
        <intercept-url pattern="/**" access="isAuthenticated()"/>

          ref="customAuthenticationProvider" />


4. Java Configuration

Next, let’s take a look at the corresponding Java configuration:

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private CustomAuthenticationProvider authProvider;

    protected void configure(
      AuthenticationManagerBuilder auth) throws Exception {

    protected void configure(HttpSecurity http) throws Exception {

5. Do Authentication

Requesting Authentication from the Client is basically the same with or without this custom authentication provider on the back end – we can use a simple curl command to send an authenticated request:

curl --header "Accept:application/json" -i --user user1:user1Pass 

Note that – for the purposes of this example – we have secured the REST API with Basic Authentication.

And we get back the expected 200 OK from the Server:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=B8F0EFA81B78DE968088EBB9AFD85A60; Path=/spring-security-custom/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 02 Jun 2013 17:50:40 GMT

6. Conclusion

In this article, we discussed an example of custom authentication provider for Spring Security.

The full implementation of this tutorial can be found in the GitHub project – this is an Maven-based project, so it should be easy to import and run as it is.

Go deeper into Spring Security with the course:


  • Stephane

    Nice article. I had to explicitly instantiate the CustomAuthenticationProvider bean though.

    • Yeah, if you don’t have claspath scanning enabled for that package – you’ll have to manually instantiate the bean. I find it easier to have scanning enabled.
      Thanks. Eugen.

  • webiyo

    Inside CustomAuthenticationProvider’s authenticate() method,

    // returning null authentication
    else {
    return null;

    is this a good idea ? what is the alternative ?? !!!

    • Good catch – it’s better to throw AuthenticationException instead of simply returning null – I updated the example. Thanks.

      • webiyo

        I am working on a project which should build two artifacts,

        1) Spring MVC based UI [WEB-Project] secured by typical spring security
        2) RestEasy based API layer [API-Project] secured by X-Auth-Token header.

        and one common java project for sharing RestEasy service interface definitions both in WEB & API projects.

        All the data access happens in API-Project, and API is using stateless spring security configuration with LDAP authentication

        WEB-Project is also using Spring Security but the authentication happens at API-Project layer and API-Project is responsible to provide authorization details to WEB-Project, authorization happens at both the layers ( duplicated ) !!!

        To achieve so I had created the CustomAuthenticationProvider which does the following,
        1) Calls the API for login with username/password acquired in WEB Project using form.
        2) Should set the WEB Session with X-Auth-Token which could be used by RestEasy API Client in WEB-Project
        3) The GrantedAuthorities should be fetched from the API-Project and put into WEB-Project per user session.


        REQUEST :

        Basically we have a API Implemented using JAX-RS with LDAP authentication using stateless Spring Security secured by a custom X-Auth-Token ( not the remember me token )

        And a UI which is not javascript based HTML5 UI but a traditional server side UI based on Spring MVC & Spring Security , this UI is getting user authorization ( which makes the scenario very complex )

        Could you come up with a demo app which has such implementation using Spring Security, JAX-RS & Spring MVC?

        This is a challenging idea to blog about !!!! which has not been discussed much on the internet !!

        Requesting you because I am a noob in such work and may end up doing id badly , where as you seem to have mastered the minute details of Spring & Spring Secueiry & REST

        • That’s an interesting scenario – it sounds like it’s functional and the MVC project does authenticate (as well as retrieve the required artifacts for authorization) agains the
          API. This pattern looks similar to an older article here on baeldung.
          I have implemented something similar with a standard MVC application with standard login and Spring Security, and an API application secured separately (also with Spring Security). I choose to have the client (js) send requests to the API directly, and only use the MVC web project to serve out the HTML.
          The API part is on github ( and I will likely move the full web project over there as well at some point (but not in the immediate future).
          Thanks. Eugen.

  • Norman

    Thanks for the tutorial. I have a question. You’ve provided the security configuration xml where authentication-provider ref=”customAuthenticationProvider” is set. Could you please point where and how bean with id=customAuthenticationProvider should be specified. Thanks in advance

  • Norman

    Figured it out. Oh I’m such a noob. That bean can be defined in the XML Security Configuration as:

  • Burak

    Can you give login.xhtml code ?

    • I wrote in detail about login here
      Hope it helps.

      • Burak

        So customauthenticationprovider uses the login.xhtml on the link you give

        • One quick note about using comments – if you need to post any large code samples – please feel free to raise an issue on github and I’ll take a look (code doesn’t render well in comments).
          Thanks. Eugen.

  • Burak

    I would like to ask a question about CustomAuthProvider, in my auth provider, I did like this

    List grantedAuths = new ArrayList();
    grantedAuths.add(new SimpleGrantedAuthority(“ROLE_ogrenci”));
    Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
    return auth;

    and my security xml

    It’s working but is it true to write like this ?

  • Hi Eugen,
    Do you know how to configure this Custom AuthenticationProvider in a java-based configuration of Spring Security? I have a class SecurityConfig where I am trying configure jdbcAuthentication, and because this I try autowire my UseDetailsService implementation in this custom class and I want see if this set up works.
    Kleber Mota

    • Hey Kleber – I have followed the new(ish) Java based configuration for Spring Security, but haven’t had a chance to use it yet. When I do – I will definitely write about it.

    • Andreas Hucknyswon

      public class SecurityConfig extends WebSecurityConfigurerAdapter {

      protected void configure( HttpSecurity http ) throws Exception {
      http.authenticationProvider( new MyAuthenticationProvider( ) );




  • Umanath M

    Fine, but we need to know more in web-service (either RestFul, or WS) with authentication which it as separate layer. It will consume from Spring MVC as presentation layer. And it also supporting token based authorization.

    • Hey Umanhath – not entirely show what you’re asking – can you try to give me some additional details please. Cheers,

  • Antonio

    Very useful, thanks a lot for sharing!

  • Amit Garg

    Can you please help me with OAuth and spring security? I want to make a stateless application. I will write my own authentication provider, for the first time authentication. I want the subsequent requests to be using the OAuth token which the client will send to the server.
    I am unable to find any good example which has implemented something like this. Do you have any sample application for such set up?

    • Hey Amit – no, I have not written about OAuth and Spring Security yet – I do plan to as some point, but it may not be very soon. I’m assuming you’re aware of the official guide and the samples. Cheers,

  • Eduardo B

    Hello, I have a similar scenario and your guide helped me a lot to succesfuly login to an external API. Now, when I get the API response, there are a lot of values that I should store “somewhere” for that user. I need this information to make sucesive calls. My first try was to access a custom User (UserDetails) object to store the values there but there was no luck. It appears that doing (after success on external login):

    User user = (User)(authentication.getPrincipal());

    freezes the app

    Maybe you could give me some guidance on this

    • Hey Eduardo – doing your own custom User implementation is relativelly straightforward and shouldn’t have any effect on your app if it implements UserDetails. Now – without a project (github, etc) that I can look at and replicate the issue, I cannot really go into more detail that that – but if you do have that up, I’d be happy to take a look. Cheers,

      • Eduardo B

        Hello Eugen, thank you very much.
        I finally took another approach and it is working very well.
        I ended extending the UsernamePasswordAuthenticationToken with the properties that I need for further communication with the API. And it has sence because these values are in fact “Tokens”.

        Then, when I need my “Tokens” on any controller, I can use:
        SecurityContext context = SecurityContextHolder.getContext();
        BizToken auth = ((BizToken)context.getAuthentication());
        String bizToken = auth.BizToken;

        Do you think of any drawback for this approach?

        Thank you again!

        • Sounds good. I wouldn’t say that the extra info can be called a “token” but the approach does work and should not be a problem. Cheers,

  • Carlos R

    Hi Eugen,

    First of all, you are creating a great and useful blog about persistence and security.

    I am creating a new application for my client and I need a special login form. This form
    is currently authenticating with a database table (users) in my local database
    (user/role tables) . I configured a static datasource (root) to connect to database and then, in the login form, I authenticate with the database table. The problem is that my client needs to create a kind
    of dynamic datasource. Thus, the authentication should be obtained from the oracle
    database user not from the user stored in my database table.

    I am currently defining this user (root) in a static properties file, so I have no
    idea about how to implement this. Is it possible in Spring security?

    Thank you!!

  • Bill


    Again, I am finding your blogs very useful. This one in particular brings up an issue for me. I am using Siteminder to authenticate, sometimes, but I must allow for a user to be authenticated from an LDAP sever if it is clear that they have not been through Siteminder. What I did was to use a filter to determine which use case I was getting and to authenticate (using spring-ldap for access) and create a wrapper HttpRequest to include SM_USER so that I could do authorization with spring-mvc. I don’t like this solution as exceptions from the Auth Filter don’t get picked up by that cool Controller Advice you showed us. What’s another way I could go?

    Thanks again for the great blog,


    • Hey Bill – glad you’re finding Baeldug useful. So – considering your usecase, one idea you can explore is defining 2 authentication providers (within the same auth manager) – these should evaluate in the order you define them and so – you can shape your authentication process by leveraging them. Hope that helps. Cheers,

  • Yodho

    Hi Eugen,

    Your post is really interesting. I’m working on an application for marketing purpose.
    I’am troubled in providing custom authentication using spring security.
    The scenario is on the login page I provide a pick list so that the user has to select one of two roles to log in (as Officer or Agent). My problem is I don’t know how to customize the authentication because Officers and Agents details are saved in two separate table.
    Would you show me a clue what am I supposed to do about it?

    • I assume that, when the user selects one role or the other, they would be re-directed to different pages after login. You can do that without having the user select their role. When a user logs in – you already know what role they have in the back end, so you can simply use that information to do the redirect. Other than the redirect, of course each user would get their correct set of authorities. As for the redirect itself – I wrote about it here. Hope it helps. Cheers,

  • Enrique

    Hi Eugen.

    I have a question about this theme.

    I want authenticate username, password AND Captcha code with Spring – Security. How to do that, because I can’t do it.


    • Hey Enrique – you can indeed do the Captcha check in a custom auth provider – but better yet, I would recommend Google – there are many good resources specifically showing you how to implement Captcha with Spring Security. Cheers,

  • Fredrik

    Thanks for this post. Just wondering, for subsequent requests do I need to pass username:password with every request? I’m trying to do it using XMLHttpRequest

    • Well, it depends on what kind of web application you’re building and what kind of authentication mechanism you’re going for. If it’s a traditional web app, using cookies for example – you wouldn’t – you would just send the cookie with each request. If it’s a stateless app, such as a REST API and you’re using things like basic, digest auth (or some custom token based auth) – then yes, you do need to send credentials. As you can see – it depends on lot on what you’re building. Hope that helps. Cheers,

  • maximo

    when i try your example i have this error message :
    The method authenticate(Authentication) of type CustomAuthenticationProvider must override a superclass

    • Hey Maximo – go ahead and get the updated version from here – that should be fixed. Cheers,

  • Ivan Masli

    How do I register the Authentication provider to Authentication manager if I choose to use Java Configuration instead of XML ?

    • Hey Ivan – a couple of things. First – we’re working on adding Java config examples to all Spring Security articles. Second – before that goes live – here’s how to do it. You need an instance of the AuthenticationManagerBuilder to then do: auth.authenticationProvider(customAuthenticationProvider);. You can get that by simply overriding the configure method of WebSecurityConfigurerAdapter in your java configuration.
      Hope that helps. Cheers,

  • Amir

    Hi. Please note that BadCredentialsException is abstract and cannot be instantiated

    • Sure thing Amir – but I don’t think we’re trying to instantiate it. I’m always updating articles to the newer versions of Spring, so maybe this was referring to an older version? Cheers,

  • Jagruti Frank

    Hi Eugen, I am runnning out of option, either it open all USER or blocks all URLS
    Option1 ) .antMatchers(“/auth/login/loginpage”).permitAll()

    this permits /login/loginpage and /agguser page to all( access is being ignored)

    OPTION 2)
    if I give .anyRequest().authenticated(); along with above lines, both the URLS are not accessible.

    Any ideas I need loginpage to be open for all user where agguser is special USER,
    Appreciate your help on this.

    This was done in lines of spring Docs

    3.4 Authorize Requests
    Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our http.authorizeRequests() method. For example:
    protected void configure(HttpSecurity http) throws Exception {
    .authorizeRequests() 1
    .antMatchers(“/resources/**”, “/signup”, “/about”).permitAll() 2
    .antMatchers(“/admin/**”).hasRole(“ADMIN”) 3
    .antMatchers(“/db/**”).access(“hasRole(‘ADMIN’) and hasRole(‘DBA’)”) 4
    .anyRequest().authenticated() 5
    // …

    There are multiple children to the http.authorizeRequests() method each matcher is considered in the order they were declared.


    We specified multiple URL patterns that any user can access. Specifically, any user can access a request if the URL starts with “/resources/”, equals “/signup”, or equals “/about”.


    Any URL that starts with “/admin/” will be resticted to users who have the role “ROLE_ADMIN”. You will notice that since we are invoking the hasRole method we do not need to specify the “ROLE_” prefix.


    Any URL that starts with “/db/” requires the user to have both “ROLE_ADMIN” and “ROLE_DBA”. You will notice that since we are using the hasRole expression we do not need to specify the “ROLE_” prefix.


    Any URL that has not already been matched on only requires that the user be authenticated

    but no joy! 🙁 any idea appreciated.

  • Daniel Severo

    Is possible that Authentication class, pass another kind of parameters? I have an application that already perform authentication using keyA and keyB that will be validated in database. I need that Authentication do not use getCredentials() as password and authentication.getName() for username, because the application does not have this fields to pass. just the keyA and keyB. that is possible?

    • Hey Daniel – if I understand your question correctly – yes, it’s possible. Have a look at the source of Authentication – you’ll notice a details Object – which can be set with the help of an AuthenticationDetailsSource.
      Hope that helps. Cheers,

  • kenyee

    What if you want to do a single signon scenario? How do you pass cookies and http request/response contexts into the authentication? Or would that be done via an interceptor instead?

    • Hey Kanyee, that’s an interesting question. However, keep in mind that most SSO implementations go beyond what you’re describing here. Spring Security has direct support for that, and of course there’s also OAuth2. The point is – it’s not something you should do manually, just by using an interceptor. It’s a more complex implementation than that, and you’re definitely better of using the support in the library than rolling it out yourself.
      Hope that helps.

      • kenyee

        Would be a good thing for a future post 😉

        • SSO? Yeah, that’s definitely a good topic to cover, it’s already on the list 🙂


    What is UsernamePasswordAuthenticationToken() doing here ? Why is this required ?

    • Hey Sunil – good question.
      That’s simply simulating an authentication provider – which needs to return an Authentication object.

      Of course a real-world auth provider will be more complex, and will probably integrate with some external system – but that’s beyond the scope of this article.
      The point here is to show a simple (but custom) auth provider – so that’s why it’s creating the Authentication object manually there.

      Hope that clears things up. Cheers,

  • Ben C.

    Hi Eugen, thank you so much for taking the time to create this example.

    As a conceptual question, is it absolutely necessary to call the authenticate method from the authentication manager? What’s the consequence of calling authenticate directly from the authentication provider?

    • Hey Ben – I’m glad the writeup was helpful.
      So, in the case of this particular example, we didn’t specifically call the authenticate method, given that we only wired the provider into the default manager, we didn’t write our own manager implementation. That will of course be called by the manager, I’m just pointing out that we didn’t do it directly/explicitly.

      But, the auth manager – auth providers structure is indeed required – meaning that there’s no way to work around that (nor should you need to).

      Hope that clears things up.