Jan
Jan

Reputation: 3401

Null on property with spring security

I have this code in my controller def user = springSecurityService.principal. The problem is that when use it like this below, the other controllers cant find the user, it returns null

class adminController{
    def springSecurityService

    def adminController(){
      def user = springSecurityService.principal
      [user:user] <-----this
    }

}

How do you make the user usable on other actions? It works if it's under each individual action like so:

class adminController{
   def springSecurityService

   def methodA(){
      def user = springSecurityService.principal
      [user:user] 
      }

  def methodB(){
      def user = springSecurityService.principal
      [user:user] 
      }
   }
  ..... and so on
}

However, this is repetitve and bad. Im using this def user = springSecurityService.principal for getting a property and displaying it in my header which is on a gsp template.

Upvotes: 0

Views: 80

Answers (1)

emilan
emilan

Reputation: 13065

For displaying user properties in your gsp template, you can create custom taglib: Below is example how to use taglib for displaying user full name.

class SimpleTagLib {
    def springSecurityService
    static namespace = "ns"

    def userFullName = {
        User currentUser = springSecurityService.currentUser as User
        if (currentUser) {
            out << currentUser.firstName + " " + currentUser.lastName
        }
    }      
}

and in your gsp template you just need to add your tag like this

.......
<ns:userFullName/>
......

P.S. You can create other taglibs for dispplaying user email, username and so on.

Upvotes: 1

Related Questions