24

Is it possible to use a jQuery ajax call to perform Forms Authentication with ASP.NET MVC? I've been unable to find any such examples.

More specifically, how do I set the auth cookie on the page (without a redirect) so I can make successive authenticated ajax requests?

2 Answers 2

18

Yes, it's possible. Just submit the login-form using the method described here by mike bosch and return a json datastructure with the returnUrl if any.

I have created a lightweight LoginResultDTO class that i return as json:

public class LoginResultDTO
{
  public bool Success {get;set;}
  public string Message {get;set;}
  public string ReturnUrl {get;set;}
}

Here's a script block from my LogOn view:

<script type="text/javascript">
        $(document).ready(function() {
            var form = $($("form")[0]);
            form.submit(function() {
                var data = form.serialize();
                $.post(form.attr("action"), data, function(result, status) {
                    if (result.Success && result.ReturnUrl) {
                            location.href = result.ReturnUrl;
                    } else {
                        alert(result.Message);
                    }
                }, "json");
                return false;
            });
        });
</script>

This will ajax wrap the logon form. Note that this is the simplest implementation of the javascript code possible but it's a place to start.

Then I have modified my LogOn action in the AccountController and in the relevant places put something like this:

if(Request.IsAjaxRequest())
{
  return Json(new LoginResultDTO{Success=true,Message="Successfully logged in"});
}else
{
  return View();
}

So this is an ultralight but rather complete version of how jquery authentication could be done in asp.net mvc.

Sign up to request clarification or add additional context in comments.

4 Comments

If I'm not doing a redirect, how would the auth cookie get set on that page?
Things are good when that ajax post returns with a success result. But you will almost always redirect after a successfull login. In the ajax scenario by assigning the url to the location.href property in javascript.
I just fired up firebug to see what's going on. When you hit the LogOn action with ajax and your login is successful, there's a set-cookie entry in the response header with the auth cookie. That's why it works.
but this doesn't work with $.getJSON ... which is the only way to make cross site authentication work ... how do you handle this one ?
0

Take a look at xVal. It can use any client-side validation library but uses jQuery Valiation by default.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.