2

That standard demos for ASP.NET MVC 3 web site user managements include the following login process:

  1. User enters auth data.
  2. Data is posted to the server.
  3. Code that handles authentication attempts checks provided data with DB.
  4. If everything is OK - calls FormsAuthentication.SetAuthCookieto set the cookies for the upcomming session requests from the browser.
  5. And redirects user to whereever.

I want to implement a purely jQuery.Ajax - ASP.NET logon mechanism.

I can call MVC site actions from js with no problem. But how do I get this FormsAuthentication.SetAuthCookie cookie data to manually, from JS code put them in a browser cookie store? How do I extract them on the server or in jQuery.ajax success code?

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174

3 Answers3

3

Using MVC 3 you can set an onclick event for your Login button and then send and ajax POST to the logon action. Have the Logon action return a JSON result and control where the user is sent from your javascript function.

[HttpPost]
public JsonResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        //Do your authentication
        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
        return Json(true);
    }

// If we got this far, something failed, redisplay form
    return Json(false);
}

In your View add an Id to your form and put a click handler on the button.

<% using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { Id = "frmLogOn" }))
   { %>
    <%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")%>
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                <%: Html.LabelFor(m => m.UserName)%>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(m => m.UserName)%>
                <%: Html.ValidationMessageFor(m => m.UserName)%>
            </div>

            <div class="editor-label">
                <%: Html.LabelFor(m => m.Password)%>
            </div>
            <div class="editor-field">
                <%: Html.PasswordFor(m => m.Password)%>
                <%: Html.ValidationMessageFor(m => m.Password)%>
            </div>

            <div class="editor-label">
                <%: Html.CheckBoxFor(m => m.RememberMe)%>
                <%: Html.LabelFor(m => m.RememberMe)%>
            </div>

            <p>
                <input type="submit" value="Log On" onclick="clicked(); return false;" />
            </p>
        </fieldset>
    </div>
<% } %>
<script type="text/javascript">
    function clicked() {
        var form = $('#frmLogOn');
        $.ajax({
            type: 'POST',
            url: '/Account/LogOn',
            data: form.serializeObject(),
            success: function (result) {
                if (result == true) {
                    alert("success");
                    window.top.location = "/Home/Index";
                }
                else {
                    alert("failure");
                }
            },
            error: function (data) {
                alert("error");
            }
        });
    }
</script>
rclement
  • 1,664
  • 14
  • 10
  • Where would the auth cookies get set in this example? How do they arrive to the client browser and get written to the cookies storage? – Maxim V. Pavlov May 10 '12 at 22:49
  • The call to FormsAuthentication.SetAuthCookie() in the LogOn action sets the cookie in the Response to the POST call to /Account/LogOn. That cookie will be created on the client side and if you then send the user's browser to a URL that requires authorization, it will use the cookie. – rclement May 10 '12 at 23:23
  • I will check and if it really does read cookies from an ajax call - will mark as answer. Thank you. – Maxim V. Pavlov May 10 '12 at 23:41
  • Indeed this is how it is implemented in ASP.NET MVC 4 Beta example. – Maxim V. Pavlov May 11 '12 at 08:43
0

Install MVC4 beta, the default Internet template provides an Ajax authentication mechanism that you can steal and put into your MVC3 app.

Or just use MVC4, since it's likely MVC4 will be released in the next couple months. There is also a go-live license for the current MVC4 beta, so you could even go live with it if you wanted to.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • I will look into it now. Why do you mention license? How does it relate to launching an MVC3 or 4 web sites? Am I legally limited to use it an any way? – Maxim V. Pavlov May 10 '12 at 21:55
  • 1
    @MaximV.Pavlov - Most betas from Microsoft do not let you use the code in production web sites, unless you get a go-live license. They have issued such a license for the MVC4 beta. – Erik Funkenbusch May 10 '12 at 22:22
0

Not jQuery - Using Forms Authentication with Microsoft Ajax

EdSF
  • 11,753
  • 6
  • 42
  • 83