0

I am doing authentication for a project. When I redirect it to another controller after authentication, it's not working. After I remove [Authorize] in the redirected controller, it's getting redirected. So, my understanding is that the authentication is not working. I followed a tutorial and in that it's getting redirected to the controller with [Authorize]. I rewatched the whole tutorial again and again and I sill can't figure out what went wrong. Please help me with this.

These are my Model classes

User.cs

        [Display(Name = "First Name")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "First name is required.")]
        public string FirstName { get; set; }
        [Display(Name = "Last Name")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Last name is required.")]
        public string LastName { get; set; }
        [Display(Name = "Email Id")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Email Id is required.")]
        public string EmailId { get; set; }
        [Display(Name = "Password")]
        [DataType(DataType.Password)]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Password is required.")]
        [MinLength(6, ErrorMessage ="Minimum 6 characters are required.")]
        public string Password { get; set; }
        [Display(Name = "Confirm Password")] 
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Passwords don't match")]
        public string ConfirmPassword { get; set; }

UserLogin.cs

        [Display(Name ="Email Id")]
        [Required(AllowEmptyStrings = false, ErrorMessage ="Email id required")]        
        public string EmailId { get; set; }
        [Display(Name = "Password")]
        [DataType(DataType.Password)]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Password required")]
        public string Password { get; set; }
        [Display(Name ="Remember Me")]
        public bool RememberMe { get; set; }

Controller Clases

AccountController

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }


        //POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(UserLogin details, string ReturnUrl = "")
        {

            string message = "";            
            using (var context = new PerformaxLiteEntities1())
            {

                var users = context.Users.Where(x => x.EmailId.ToLower().Equals(details.EmailId.ToLower())).FirstOrDefault(); 
                if(users != null)
                {
                    if( details.Password != null && string.Compare(Crypto.Hash(details.Password), users.Password) == 0)
                    {
                        int timeOut = details.RememberMe ? 525600 : 30; 

                        var ticket = new FormsAuthenticationTicket(details.EmailId, details.RememberMe, timeOut);
                        string encrpted = FormsAuthentication.Encrypt(ticket);

                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrpted);
                        cookie.Expires = DateTime.Now.AddMinutes(timeOut);

                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);


                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return Redirect(ReturnUrl); 
                        }
                        else
                        {
                             //Debugger hits here. But redirection is not happening. 
                             //It only happens when I remove [Authorize] in Home Controller.
                             return RedirectToAction("Index", "Home" );
                        }
                    }
                    else
                    {
                        message = "Invalid credentials"; 
                    }

                }
                else
                {
                    message = "Invalid credentials";
                }
            }
            ViewBag.Message = message;
            return View();
        }

Home Controller

[Authorize]
public class HomeController : Controller {

    [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
    public ActionResult Index()
    {

        return View();

    }
}

I have also added this in my Webconfig file.

<authentication mode="Forms">
      <forms cookieless ="UseCookies" loginUrl="~/Account/Login" 
       slidingExpiration="true"></forms>
</authentication>

I am new to Authentication and I have been sitting with this problem for some days. Kindly help me out.

StarLord
  • 707
  • 1
  • 8
  • 21
  • You probably need to set a path on the cookie, otherwise it will be associated with the path of the login request, and the browser will not send the cookie with the request to the home controller. Try adding `cookie.Path = "/"` in your Login (post) method. – user1429080 Jun 15 '20 at 14:40
  • @user1429080 When I debugged, cookie.Path is by default, "/". Even after adding `cookie.Path = "/" ` , redirection is still not happening. – StarLord Jun 18 '20 at 08:59

3 Answers3

0

you never actually make user login in owin

 var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        return RedirectToLocal(returnUrl);
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.RequiresVerification:
        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
    default:
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
}

so in you account controller use usermanager and if user is logged in by user manager then whole authorization will work

Alireza Madad
  • 151
  • 2
  • 13
  • I wasn't trying to make user login using owin. I was trying through Asp.Net Forms Authentication. I am still not able to figure out what went wrong in the code. – StarLord Aug 05 '20 at 09:29
0

To read the FormsAuthentication cookie, normally you would hook the AuthenticateRequest event in a HttpModule or the Global.asax and set up the user IPrinciple context.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if(authCookie != null)
        {
            //Extract the forms authentication cookie
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    
            // If caching roles in userData field then extract
            string[] roles = authTicket.UserData.Split(new char[]{'|'});
    
            // Create the IIdentity instance
            IIdentity id = new FormsIdentity( authTicket );
    
            // Create the IPrinciple instance
            IPrincipal principal = new GenericPrincipal(id, roles);
    
            // Set the context user 
            Context.User = principal;
        }
    }

source How can I manually create a authentication cookie instead of the default method?

-->IIdentity id = new FormsIdentity( authTicket ); Context.User = principal;<-------

if (HttpContext.Current.User.Identity.IsAuthenticated) []-_-[] nothing else will work probably otherwise you want to try there is hint override authorize attribute

Alireza Madad
  • 151
  • 2
  • 13
  • //Debugger hits here. But redirection is not happening. //It only happens when I remove [Authorize] in Home Controller. return RedirectToAction("Index", "Home" ); you redirect to home/index and back to accoount/login thats why because user is not authenticated – Alireza Madad Aug 12 '20 at 03:47
  • @ Alireza Madad I don't understand how I am redirecting back to Account/Login. Anyways, I have the found out the issue with the code. Thanks for the help. Much appreciated:) – StarLord Aug 13 '20 at 12:43
  • 1
    @StarLord yaw LiveLongAndProsper xD – Alireza Madad Aug 27 '20 at 04:10
0

I have found out the issue with this. In my Web.config Forms Authentication was disabled by default. When I started the project, I gave Identity based authentication. I am assuming it's because of that Forms Authentication was disabled.

<system.webServer>
    <modules>
      <remove name="FormsAuthentication"/>
    </modules>
</system.webServer>

Comment out or delete the above lines in the Web.config and you are good to go.

If you are still having problems then, make sure Form Authentication is enabled in IIS Manager. In order to check that, Go to start, type IIS, then select IIS Manager, go to Authentication and check Forms authentication is enabled.

IIS Manager screenshot

StarLord
  • 707
  • 1
  • 8
  • 21