Search code examples
asp.netasp.net-mvc-3jqueryasp.net-authentication

Authenticate ASP.NET user session with javascript


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?


Solution

  • 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>