Archive | December, 2013

Custom Authentication with the Grails Spring Security Core Plugin

2 Dec

In my project, i need to add feature which user can choose what method to login. Whether login with user details (username, password) or card details (card no and pin). For login with user details, i think it’s already a common case since it’s default from grails spring security core.

I google how to create custom login and found bellow article which is great and help me a lot, thanks to the writer:

to summarize the article, steps to do:

– create CardAuthenticationToken (custom authentication object)

– create CardAuthenticationFilter (custom filter)
1. check whether request URL contains “j_spring_security_card_check” or not. If it doesn’t, it will call the next filter in the chain. If it does, the rest of the steps will execute.
2. build CardAuthenticationToken and pass it AuthenticationManager to authenticate it.
3. if no AuthenticationException is thrown then it means success and return the authentication object.
4. call the success handler that will redirect to the appropriate place.

– registering CardAuthenticationFilter in BootStrap
SpringSecurityUtils.clientRegisterFilter(‘cardAuthenticationFilter’, SecurityFilterPosition.SECURITY_CONTEXT_FILTER.order + 10)

– registering CardAuthenticationFilter in resources
cardAuthenticationFilter(CardAuthenticationFilter) {
def conf = SpringSecurityUtils.securityConfig
filterProcessesUrl = ‘j_spring_security_card_check’
authenticationSuccessHandler = ref(‘authenticationSuccessHandler’)
authenticationFailureHandler = ref(‘authenticationFailureHandler’)
authenticationManager = ref(‘authenticationManager’)
sessionAuthenticationStrategy = ref(‘sessionAuthenticationStrategy’)
allowSessionCreation = conf.apf.allowSessionCreation

– create CardAuthenticationProvider
1. check to see if the Authentication object is of type CardAuthenticationToken. If it isn’t, the ProviderManager will try the next provider that is registered.
2. retrieve the card no and pin from the Authentication object.
3. use the CardAuthenticatorService to check it.
4. if it’s correct then get the user related to that card number.
4. build and return an Authentication object (UsernamePasswordAuthenticationToken) to the filter that will be placed into the SecurityContextHolder.

– registering CardAuthenticationProvider in Config
grails.plugins.springsecurity.providerNames = [

– registering CardAuthenticationProvider in resources
cardAuthenticationProvider(CardAuthenticationProvider) {
cardAuthenticatorService = ref(‘cardAuthenticatorService’)
userDetailsService = ref(‘userDetailsService’)