Tuesday, March 4, 2014

Add Token Based Authentication on Spring Security

Problem I have an application which has already implemented Basic Authentication using Spring Security.
Now as part of a new requirement I have to enable a Token based authentication as well.
My first task was to updgrade to Spring 3.0.7 and to Spring Security 3.1.3 among other dependicies that needed an update as well.
After that, let's go to the meaty part of this implementation :)
While researching I couldn't find any example, only pieces, that's why I'm publishing and sharing my findings with all the community:

At least I knew that I had to implement another Authentication Provider (that's why I needed to Upgrade my App) and something to catch the event of login and tell Spring to perform another authentication (like a Filter, maybe?)

This is my implementation: Spring's config
PingIdentityTokenValidatorImpl (Validates Given token)
KaplanOAuth2UserDetailsService (Performs Authentication, generates user following spring security standards)
KaplanCustomOncePerRequestFilterFilter (This filter does the trick) Just add it to your security configuration in the right place of the chain of execution and you're set Although, my original approach was to extend from AbstractAuthenticationProcessingFilter, however I saw it being invoked multiple times per request (it didn't bother me), but that wasn't good enough for me, also it was more complex :P