How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity?

后端 未结 1 841
抹茶落季
抹茶落季 2020-11-30 00:27

Apologies and Thanks in advance for this question! I am still new to SO.

I have been working on a web application using MVC5, EF6, and VS 2013.

I spent some

1条回答
  •  执念已碎
    2020-11-30 01:04

    So here's what login will basically look like in RTM (code copied from the ASPNET Identity sample code):

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
    
            // If we got this far, something failed, redisplay form
            return View(model);
        }
    
        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }
    

    EDIT: And you need the follow changes in your Startup.Auth.cs:

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
    

    0 讨论(0)
提交回复
热议问题