Spring security ajax login in Grails

Posted By : Akash Sharma | 25-Aug-2013

In this blog I am going to share ajaxified login of spring security in grails.

I also want to describe some basic features of spring security that how it internally works while a user tries to login.

Before going forward I suppose that you already have spring security configured with your grails project if not use this .

 

By default the login page of application is rendered through /login/auth.

When a user tries to submit username and password on login page, it hits a filter j_spring_security_check. This filter validates the username and password.If user is valid then a redirect to /login/ajaxSuccess occurs (this URL is configurable) else a redirect to /login/authfail occurs (this URL is configurable).

 

By configuring url mapping we can configure a redirect to some other page of application when a user validates successfully.But when a user is invalid then user is redirected to /login/authfail action with some login_error and it again redirects to /login/auth?login_error=1 .The error message can be varied from the type of validation error.

 

Now I am going to discuss how can we ajaxify this invalidation of user and not refreshing the whole page.

In simple terms I am going to hit an ajax call to j_spring_security_check filter and depending on its response I will do appropriate actions.

 

For making things simple, I have created a new action as “authenticateUser” in login controller and corresponding view “authenticateUser.gsp”.

 

The code for my custom action

def authenticateUser={
def config = SpringSecurityUtils.securityConfig

if (springSecurityService.isLoggedIn()) {
redirect uri: config.successHandler.defaultTargetUrl
return
}

String view = 'authenticateUser'
String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
render view: view, model: [postUrl: postUrl,
  rememberMeParameter: config.rememberMe.parameter]
}

 

This is just the copy of /login/auth action.I needed this code because I want to get the url of j_spring_security_check filter.

The corresponding view for authenticateUser.gsp

<head>
<script type="text/javascript" src="${resource(dir: 'js', file: 'jquery-1.8.3.js')}"></script>
</head>
<div id='ajaxLogin'>
  <form  method='POST' id='ajaxLoginForm' name='ajaxLoginForm' >
     <p>
        <label for='username'>UserName</label>
        <input type='text' name='j_username' id='username' />
     </p>
     <p>
        <label for='password'>Password</label>
        <input type='password' name='j_password' id='password' />
     </p>
     <p>
        <label for='remember_me'>Remember me</label>
        <input type='checkbox' id='remember_me' name='_spring_security_remember_me'/>
     </p>
     <p>
      <input type="button" onclick='authAjax(); return false;' value="login" />
     </p>
  </form>
   <div id='errorLoginMsg'></div>
</div>


<script type='text/javascript'>
function authAjax()
{
var formdata = $('#ajaxLoginForm').serialize();
var dataUrl = "${postUrl}"       
jQuery.ajax({
type : 'POST',
url :  dataUrl ,
data : formdata,
success : function(response,textStatus)
{
emptyForm();
       if(response.success)
   {
   var redirectUrl="${ createLink(action:'blogList' ,controller:'blog') }"; 
        window.location.assign(redirectUrl);
       }
       else
   {
        $('#errorLoginMsg').html(response.error);
   }
},
error : function(
XMLHttpRequest,
textStatus,
errorThrown) {
}
});
}


function emptyForm()
{
$('#username').val('');
$('#password').val('');
$('#remember_me').val('');
}
</script>

 

How does it work:

 

After hitting ajax call to filter, if user is valid,we get a response in json form with two values.A boolean parameter name success with value true and a string parameter name username with the name of the logged in user.This response got from action ajaxSuccess.

If user is not valid then the response is in json form having a parameter name error with the value as type of error occurred while login.This response got from action authfail.

Both ajaxSuccess and authfail actions are configurable.

 

In my custom gsp I redirected the page to /blog/blogList which is home page of logged in user in my application.You can configure this part on the basis of your requirement.

 

 

Akash Sharma

About Author

Author Image
Akash Sharma

Akash is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Akash loves playing Cricket and Tennis

Request for Proposal

Name is required

Comment is required

Sending message..