Shiro/Grails Tips

The Shiro plugin page in the Grails plugin repository has great information. Here are a couple of additional items I picked up during an implementation on my current project:

1. Filter every action except ‘x’ on a given controller

	    myFilter(uri: '/myController/**') {
	      before = {
	        if (!controllerName || actionName == "anOpenAction" || actionName == "anotherOpenAction") return true

	        // Access control by convention.
	        if (!isErrorPage(controllerName, actionName)) {
	          accessControl()
	        }
	      }
	    }

In this case, we’re taking advantage of common properties in grails. Basically, we’re filtering actions on myController. The first ‘if’ clause (!controllerName) filters for direct/default controller views, ignoring direct views. The other clauses are saying ‘if we’ve hit this filter, but the actionName is ‘anOpenAction’ or ‘anotherOpenAction’, let the request through.

2. Simple landing pages – enhancing the ‘free’ Shiro AuthController

If there is no target URI on the user’s original request to login, meaning, if they weren’t challenged and instead clicked on a ‘login’ link, a simple way to control where they are directed (assuming the goal is not to direct them to ‘/’) is as simple as this (with source from the AuthController):

	// If the user came to the login page via redirect (security filter caught an attempt to
	            // go to a restricted area of the site), then send them back from whence they came.
		        def savedRequest = WebUtils.getSavedRequest(request)
		        if (savedRequest) {
		            targetUri = savedRequest.requestURI - request.contextPath
		            if (savedRequest.queryString) targetUri = targetUri + '?' + savedRequest.queryString
		            println "Target URI, from saved request: ${targetUri}"
		        }
		        else {
		            // If a controller redirected to this page, redirect back
			        // to it. Otherwise redirect to an appropriate URI depending on the
		            // role of the user who just logged in.
		        	if(params.targetUri) {
		        		targetUri = params.targetUri
		        	}
		        	else {
		        		targetUri = //some bit of code that determine the URI from the current user, etc.
		        	}
		        }

Where that last reference of ‘targetUri’ is somehow set to where you want your newly-authenticated user to land.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s