Search code examples
grailsspring-securitygrails-plugin

How to use Grails Spring Security Plugin to require logging in before access an action?


I know that I can use annotation or Request mapping to restrict access to an ACTION by some specific ROLES. But now I have a different circumstance.

My scenario is: every user of my site can create posts, and they can make their own post public, private, or only share to some other users. I implement sharing post by a database table PERMISSION, which specify if a user have the right to view a post or not.

The problem arises here is that when a customer access a post through a direct link, how can I determine he/she have the privilege to view it? There's 3 circumstances:

  1. The post is public, so it can be viewed by anyone (include not-login user)
  2. The post is private, so only the login-owner can view it
  3. The post is sharing, it means only the login-user that is shared and the owner can view it.

I want to process like this:

  1. If the requested post is public: ok.
  2. If the requested post is private/sharing: I want to redirect the customer to the login page; after logging in, the user will be re-direct to the page he wants to see.

The problem here is that I can redirect the user to login controller/ auth action, but after that I don't know how to redirect it back. The link to every post is different by post_id, so I can't use SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl

Could anyone know a way to do this?


Solution

  • I have found a quick workaround for this problem:

    1. If the user is logged in: check the user's privilege, and return the appropriate result.
    2. If the user is not logged in: At view action, set the post_id by:

      session.post_id = 8

    3. Redirect the user to the Login Controller/ Auth action.

    4. At checkrole action(which is my grails.plugins.springsecurity.successHandler.defaultTargetUrl in Config.groovy), if session.post_id exists, use it to build the link for re-directing to the view action. Before redirecting, clear the session.post_id.