0

I would like to implement a login form that has use Ajax.Beginform. I have implemented the code, but I have a problem, after an ajax post and seting up the Authentication cookie, the controller returns the view, but the IsAuthenticate method retuns false at the _Layout view:

Here is my Controller:

   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;
    using System.Web.UI.WebControls.WebParts;
    using USCSAR.Manager;

    namespace USCSAR.Controllers
    {
    public class HomeController : Controller
    {
        Manager.ManagerJMBG manager = new ManagerJMBG();

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View(new ViewModel.ViewJMBG());
        }


        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(string _jmbg)
        {
            string errorMassage = "Neispravan, logicki netacan unet JMBG !";

            if (ModelState.IsValid && !string.IsNullOrEmpty(_jmbg))
            {
                bool valid = Common.JMBG.IsValid(_jmbg);

                if (!valid)
                {
                    return View("LoggerManagerPartial");
                }

                try
                {
                    bool isUserExists = manager.IsUserExist(_jmbg);

                    if (!isUserExists)
                    {
                        manager.CreateNewUser(_jmbg);
                        FormsAuthentication.SetAuthCookie(_jmbg, true);
                        return View("LoggerManagerPartial");
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(_jmbg, true);
                        return View("LoggerManagerPartial");
                    }
                }
                catch (Exception)
                {
                    return View("Error");
                }
            }
            else
            {
                ModelState.AddModelError("", "JMBG korisnika je neispravan!");
                return Json(errorMassage);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

    }
}

The _Layout:

@model USCSAR.ViewModel.ViewJMBG

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
        <body>
            <header>

                <div id="LoginContent" style="background-color: gray; color: black">
                    @Html.Partial("LoggerManagerPartial", Model)
                </div>

            </header>


            @RenderBody()

            @Scripts.Render("~/bundles/jquery")
            @RenderSection("scripts", required: false)
            <script src="~/CustomScripts/FailureLogin.js"></script>
        </body>
    </html>

LoggerManagerPartial :

@if (Request.IsAuthenticated)
{
    <strong>@Html.Encode(User.Identity.Name)</strong>
    <br />
    @Html.ActionLink("Odjavi se", "Logout", "Home");
}
else
{
    using (Ajax.BeginForm("Login", "Home", new AjaxOptions
    {
        HttpMethod = "POST",
        OnFailure = "FailureLogin(data)",
        OnSuccess = "SuccessLogin()",
        InsertionMode = InsertionMode.InsertAfter,
        UpdateTargetId = "LoginContent"
    }))
    {
        <input type="text" id="_jmbg" name="_jmbg" onkeypress="IsNumberKey(event)" />

        <input type="submit" value="bla" />
    }
    <br/>
    <label id="errorMassage">Error Label</label>
}

thnx

Wasyster
  • 2,279
  • 4
  • 26
  • 58

1 Answers1

1

I think the problem may be related to Request.IsAuthenticated - see this question How does Request.IsAuthenticated work?.

According to an answer to this question: asp.net mvc authentication cookie issue you need to use

HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

to get the cookie and then decrypt it and get username with

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData

Hope that helps.

Community
  • 1
  • 1
Michael Lykke
  • 111
  • 1
  • 7