How to make a custom Username Password Authentication Filter with Spring Security



Basically I’ll show you how to use Spring Security and how to customize it if you want. First we’ll implement the basic authentication with basic responses and other stuff, and I’ll show you how to customize the login and logout process as you wish (smile)


Simple Authentication

After you added the required dependencies described on Spring’s website, you want to create a WebSecurityConfig class, that tells Spring Security how you want to authenticate your users, and what you want to do

  • after a successful login,
  • an unsuccesful login, and
  • after a successful logout.

Let’s say we have a pretty simple Controller we want to protect with authentication.


And the WebSecurityConfig


As you see there is a UserService that, for now, has a really simple implementation

By implementing the ‘loadUserByUsername’ function, you tell Spring the password of your user, and the authorities it should grant to the authenticated user. For now authorities is an empty List. Spring will compare your user’s password, and the password form the API. If they match. By default a ‘PlaintextPasswordEncoder’ used by Spring, but later i’ll show you how to encode your passwords (smile)

After you added these lines to your project, you can try out the following actions from your favourite REST Client (I use Postman)

url - behavior - spring password

Reading request body

In the next step we’ll change our application to read the request body instead of the query string.


You can only read the request body’s stream once. If you want to use the data in different services for example, you should cache the body somehow (you can find a lot of solutions if you google it). Let’s assume that we only want to read the body once (smile)

First we need a CustomUsernamePasswordAuthenticationFilter and we have to tell Spring to use our filter instead of the default one.



This is how our custom filter looks like. It is as simple as it seems, we just have to parse the request body into a Java class, create a token, and then use the default authenticaton method. After we created this class, we only have 2 tasks left. First is to provide our bean, second is to tell Spring to use our filter instead of the default one. To reach this we change out WebSecurityConfig class like this



Note the commented lines. After you provided your custom filter, you can no longer use the Spring HttpSecurity builder. If you still use it, you’ll configure the default Filter, not yours!

We tell Spring to use our implementatin by the “addFIlterBefore” function.

After this little modification, the test APIs work the same way, the only difference is that you should provide ‘login’ and ‘password’ params in the POST request body (and not the query string)

Encoding passwords

First we have to change our UserDetailsService a little


Like this, our UserService provides a mock user that has an encoded password.

Second we have to change our WebSecurityConfig

As you see, we changed the configureGlobal a little bit, and added a DaoAuthenticationProvider bean. We have only one more thing to do, we have to provide our favourite PasswordEncoder in a separate class, like:


After these modifications, the same APIs should work like before. The only difference is on the backend side, we “stored” our users with encrypted passwords, which is nice. (smile)


As you see, adding a custom authentication is not hard with Spring, the hard thing was to put all of these together. As far as I saw, no one on the internet wanted to customize the login process like I described above. I hope you found this post useful! If you want to take a look at the full example project, just click here.

See you later! (smile)

About us

Wanari is a custom software development studio based in Budapest, founded in 2000. Today we are a team of 35 and this is our tech blog. We share software development insights regularly. If you want to read more posts like this, keep up with #TeamWanari on Facebook or LinkedIn.

  • Slovvik

    Hi, great post. It helped me a lot! But it seems that loginFailureHandler is not working. I sent 401 status error code with message but I always receive 403 without message. I suppose that this call is somewhere intercept, but I can’t found where.

    • Alex Sükein

      Hi thanks for the compliment, I’m glad you liked it!

      My understaning is that if you’re unauthenticated, you get 403 (loginFailureHandler) and if you are unauthorized, you get 401 (accessDeniedHandler). Now if you have trouble with login, your issue is on the authentication side, rather than the authorization side. If I am right here, I think you should be looking for the trouble at accessDeniedHandler (for more on this, I recommend We will soon provide more info on this, too!

      If I didn’t get this right, please let me know with a more detailed problem description and I’ll look into the issue further!

      • Slovvik

        Hey, thanks for answer, You were of course right 🙂 Great tutorial 😛 If I can suggest some thing, it would be nice if You came with a second tutorial how to integrate to this Facebook or some other login provider 🙂

  • Nho Anh

    how do i login by email instead of username?

    • Alex Sükein

      First of all thanks for reading my post, I really appreciate it! 🙂

      All you have to do is rename the LoginRequest’s login attribute to email. After that (if you want) you can validate the e-mail in the UserService’s loadUserByUsername function.

      I think what confuses you is that Spring Security calls it ‘username’ and ‘password’, but that’s just an interface, so you can call you variables whatever you want.

      Hope this helps, if you have more questions feel free to ask!

      • Nho Anh

        Thanks @wanari_suxy:disqus so much.

  • Ravi prasad

    Thank you very much for this post! It helped exactly the way I wanted in my personal Project.
    I need a suggestion!!

    My front end is Angularjs and backend I am using Springboot+springWebMVC+springsecurity+springdataJPA. Now, based on the successful login, I will have to enable or desable some actions on the UI like hiding/showing Login/Logout and also based on Role I need to show Edit/Delete for the logged in User.
    So, can you suggest some references or best practices to handle this.
    Appreciate your response in advance.

  • Pingback: smettere di fumare()

  • Pingback: example()

  • Raja Gosh

    I follwed RequestBodyReaderAuthenticationFilter but I am getting null userName when I amtrying get using request.getParameter(“userName”) where could be the issue?

    • Alex Sükein

      First of all: request.getParameter(“userName”) gets the value from the query string and not from the request body. So if you provide your ‘userName’ and ‘password’ in the request body, then it should appear in the instance of LoginRequest class (after renaming the ‘login’ attribute to ‘userName’).

      Second of all: if you want to provide the credentials in the query string, then you should modify the Spring’s default behaviour in the WebSecurityConfig class by calling ‘.usernameParameter(“userName”)’.

      If none of the above is the solution for your issue, then please provide some more information! (source code, postman API call, etc.)

      Also, thanks for reading my post 🙂 Hope this answer helps you.

  • Jacek Kowalski

    How to get password in UserDetails loadUserByUsername ?