smeeb
smeeb

Reputation: 29487

Grails 3 interceptors for authentication?

I am experimenting with Grails 3 Interceptors. Given the following interceptor:

class AuthInterceptor {
    AuthInterceptor() {
        matchAll().includes(controller:"account")
    }

    // Intercept anything under /account.
    boolean before() {
        User user = SimpleSecurityUtils.getCurrentUser()
        if(user != SimpleSecurityUtils.anonymous) {
            // Only get here if the user is currently authenticated. Redirect them to where they want to go.
            true
        } else {
            redirect(controller: auth, action: signin)
            true    ??
        }
    }

    boolean after() { true }

    void afterView() {
        // no-op
    }
}
  1. matchAll().includes(...) doesn't actually exist on the Matcher object. So how do I actually say "only intercept requests to the AccountController"?
  2. If you follow the auth logic, if the user is currently anonymous (not logged in), I want to redirect them to the AuthController#signin action, which will present them with a login screen. It doesn't appear that the redirect(...) closure is available to interceptors...so how do I perform this redirect safely? Furthermore, how do I "save off" the URL we are currently intercepting so that, after successful login, the user can yet again be redirected to the originally-requested URL?

I say safely above because I've had issues with Grails CannotRedirectExceptions being thrown if too many redirects keep getting tossed around, and those errors are usually assuaged by returning after performing a redirect per this previous answer.

Upvotes: 3

Views: 1965

Answers (1)

bcswartz
bcswartz

Reputation: 264

For #1, match( controller: "account" ) should do the trick. Don't know the answer to #2.

Upvotes: 1

Related Questions