Search code examples
grailsspring-securitygrails-2.0grails-controller

Grails practises for ensuring that a user is who they say they are (spring security)


I am using the spring security plugin and thus am able to make use of the method springSecurityService.currentUser to access the current logged in user. However, i assume that obtaining the current user within each controller action and then performing actions based on the returned user is not the recommended best practise.

Examples:

  1. logged in user clicks link to their profile page - controller obtains current user and returns data to populate profile page for this user.

  2. logged in user changes status on profile page - controller obtains current user, from this finds their profile and then updates the status on this profile.

ETC

This should ensure that a user accessing a page is who they say they are - as there is no passing of User Id or other identifying information from a client. However, obtaining the user in each action seems wrong, and i havent seen many examples of code which do this. Should I be using filters to intercept requests or some other flow/practise?


Solution

  • springSecurityService.currentUser exists for that exact purpose. The reason you need to retrieve the current user each time is because controller actions are stateless. Yeah, there's a session at play which maintains some state, but what I mean is that there's no direct transfer of state from one controller action to another. So, it is in fact best practice to obtain the current user each time.

    What happens is the client provides a cookie, usually named JSESSIONID, to Grails. Grails then uses that to restore any session data, which essentially leads to springSecurityService.currentUser being able to provide the current user. So while the client does not pass the user ID, it does pass a session ID, which indirectly is identifying information.