Search code examples
grailsspring-security

Cannot invoke method isLoggedIn() on null object


I actually have two spring security related question.

1, I have the below code in my controller for changing password

def changePassword() {

        if (!securityService.isLoggedIn()) {
            redirect(action: 'auth', controller: 'login')
            return
        }
}

when i hit save button after confirming the new password it generates te following error

NullPointerException occurred when processing request: [POST] 
Cannot invoke method isLoggedIn() on null object.

Now My question is where am i wrong?

2, my second question is also similar am trying to get the current user like this

User currentUser = securityService.getCurrentUser()
            currentUser.gender = gender
            currentUser.save()

But still its generating the same error
Cannot invoke method getCurrentUser() on null object

NOTE:- I am using grails 2.4.4 and spring security 2.0-RC4.

UPDATE:- I did include def securityService in my controller/service


Solution

  • Just add 'def springSecurityService' in your controller

    Class UserController{
    
      def springSecurityService
    
      def changePassword(){
          //You can access springSecurityService now
        if (!springSecurityService.isLoggedIn()) {
            redirect(action: 'auth', controller: 'login')
            return
        }
      }
    }