Search code examples
javascripthtmlasp.net-mvcauthenticationasp.net-authentication

html/Javascript Clientside User Login


I am adding authentication to my web application. It is an asp.net mvc single page application. Currently the web application is using the asp.net mvc for only one thing, authentication. I check the Request.IsAuthenticated in the AppController, if it isnt authenticated than I serve the login page (else I save the app.html page). In my AccountController I have the following Logon Action:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            //VALIDATE USER NAME AND PASSWORD                
            if (Repository_Security.CheckUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "App");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

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

Really its just taking a user name and password and validating against the database. Than sets the AuthCookie if it passes.

My question is, is this possible if I do this entirely clientside in the browser in javascript and ajax data calls? Than be able to add a check in my clientside code to see if the user is authenticated, else throw them to a login page?

Any ideas? thanks.


Solution

  • Yes, and MVC is perfect for working clientside Ajax.

    You can modify your controller to return JSON, and with a jquery ajax call you can process the returned json using clienside javascript.

    Change the last line (return View(model)) to look something like the following

    return Json(new {IsSuccess=successVariable, RedirectUrl=myRedirectUrl, Message=failedErrorMessage});
    

    Adjust your Redirect lines to instead set myRedirectUrl variable.

    Update

    If you want to get rid of MVC in your project (as it's an overkill for such a simple task), add a web service (asmx) to your site. Inside create a webmethod similar to following:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public LogonResponse Logon(LogonModel model){
        ... do login logic as your original code...
        return new LogonResponse() { IsSuccess = successVar, RedirectUrl=myRedirectUrl, Message=failedErrorMsg};
    }