Search This Blog

Thursday, January 27, 2011

Getting user credentials in a grails application using Spring Security


Getting user credentials in a grails application using Spring Security is pretty easy

If you followed the instructions given for spring security plugin then LoginController takes care of storing the user credentaisl for you.
To retrieve the stored credentials you need to do these
1. Import SecurityContextHolder
import org.springframework.security.core.context.SecurityContextHolder as SCH

2.Get the principal
SCH.context?.authentication?.principal

3. once you get hold of the principal object you can retrieve and use any creds.

SCH.context?.authentication?.principal?.username


Update: Thanks for Burt for pointing out how I can make this easier.

I can use SpringSecurity service injected  by declaring
def springSecurityService

Then this can be used like 
                     springSecurityService.principal 
to get the principal.




2 comments:

  1. You're much better off using SpringSecurityService

    ReplyDelete
  2. Yes Burt you are right.Thanks for pointing this out.
    Will update my post.

    ReplyDelete