Grails SpringSecurityService: Authenticate via Code manually

Use case

After struggling around for more than one hour to find out a good practise to login a user within the springSecurity-architecture manually.
I found this helpfull post in the Grails user mailing list:
http://grails.1312388.n4.nabble.com/Automatically-logging-a-user-in-after-ajax-registration-with-Spring-Security-td3166809.html

Solution

// Find bu username
User user = User.findWhere( username: params.username )

// Check if passwords equal
if( user.password == springSecurityService.encodePassword( params.password ) ) {

  def request = RCH.currentRequestAttributes().currentRequest
  def response = RCH.currentRequestAttributes().currentResponse                

  // Get user details
  UserDetails userDetails = springSecurityService.getUserDetailsService().loadUserByUsername( params.username )

  // Build Token
  def authentication = new UsernamePasswordAuthenticationToken( userDetails, params.password )
  authentication.details = new WebAuthenticationDetails(request)
  SCH.context.authentication = authentication                

  // Do the authentication adn store in session (otherwise the user is only logged in for this request)
  request.session.setAttribute( AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY, user.username )
  authenticationManager.authenticate( authentication )

  // optional remember me
  //rememberMeServices.loginSuccess request, response, authentication
}
Tagged with: , , , , ,
Posted in Grails, Groovy, SpringSecurity
One comment on “Grails SpringSecurityService: Authenticate via Code manually
  1. Jon Polaski says:

    This saved me a lot of aggravation. Thanks very much for this post!

Leave a Reply to Jon Polaski Cancel reply

Your email address will not be published. Required fields are marked *

*

Anti-spam protection

Prove that you are Human by typing the emphasized characters:


Protected by Gab Captcha 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>