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

1.1k Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

When working on my project, I found the following way to check the log-in status.

def springSecurityService

boolean canEdit() {
   boolean isLoggedIn = springSecurityService.isLoggedIn()
   if (!isLoggedIn) { return false }
      boolean hasAdminOrCuratorRole = userService.isLoggedInUserACurator() || userService.isLoggedInUserAAdmin()
   hasAdminOrCuratorRole
}

Hope this helps!