Search code examples
grailsspring-securityinterceptorgrails-plugingrails-3.1

What is the best way to check if the user is logged in or not in grails Spring Security?


I would like to check if the user is logged in or not.I have integrated interceptor in most of the projects to check if user is logged in . But this does-not work well with AJAX request and matching all the controllers in the interceptor causes filter to be applied for all controllers including /static/** ,where in this case i will have to exclude (.excludes(uri: "/static/**")) .Is this the correct and standard way of doing?

LoginInterceptor() {
        matchAll()
                .excludes(controller: "login") 
                .excludes(controller: "signUp") 
                .excludes(uri: "/static/**")
                .excludes(uri: "/assets/**")
    }
    boolean before() {
        if (!springSecurityService.isLoggedIn()) {
            flash.message="You need to login to access furthur pages"
            redirect( controller: 'login',action: 'auth');
            return false
        }
        true
    }

    boolean after() { true }

    void afterView() {
        // no-op
    }

The above code doesnot work with the AJAX request . How do i make a generic interceptor which works well with both AJAX and WEB request? And is this a standard way of monitoring request for logged in?


Solution

  • If you use spring security plugin. You can do it by configuring security config. You can find more here

    For ajax request you can check return code and if it is == 403, you can redirect user to the login page.