如何使用 AspNet.Identity 通过 Asp.Net MVC5 RTM 位登录/验证用户?

2023-12-30

我一直在使用 MVC5、EF6 和 VS 2013 开发 Web 应用程序。

我花了一些时间升级到发布后的 RC 位。感谢所有精彩的帖子:例如。解耦 Microsoft.AspNet.Identity.* https://stackoverflow.com/questions/18727317/decoupling-microsoft-aspnet-identity?lq=1 and 将 asp.net MVC 从 5.0.0-beta2 更新到 5.0.0-rc1 https://stackoverflow.com/questions/18416915/updating-asp-net-mvc-from-5-0-0-beta2-to-5-0-0-rc1/18426574#184265 !

以我无限的智慧,我决定转向 @Hao Kung 在这里发布的 RTM 位:如何尽早访问即将到来的 Asp.Net Identity 更改? https://stackoverflow.com/questions/18793746/how-can-i-get-early-access-to-upcoming-asp-net-identity-changes。我想当我们最终收到 RTM 版本时,我可以省去麻烦,并且不会落后太远。

这要么是一场噩梦,要么我完全错过了一些东西(或两者兼而有之),因为我无法弄清楚与 RC1 相关的基本任务。

虽然我似乎是通过控制器登录用户(Asp.Net Identity RTM 版本中的 Microsoft.AspNet.Identity.Owin.AuthenticationManager 在哪里? https://stackoverflow.com/questions/18801120/where-is-microsoft-aspnet-identity-owin-authenticationmanager-in-asp-net-identit) ...我的 WindowsIdentity 始终为空,并且在我调用 SignIn 后未经过身份验证。 user 和 ClaimsIdentity 对象已正确填充。

这是我正在调用的操作方法(为了完整性,将属性移动到局部变量):

[HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public virtual async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid) {
        var userManager = new UserManager<EtdsUser>(new UserStore<EtdsUser>(new EtdsContext()));
        var user = userManager.Find(model.UserName, model.Password);
        if (user != null) {
            var authenticationManager = HttpContext.GetOwinContext().Authentication;
            authenticationManager.SignOut(new[] {DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ExternalBearer});
            var claimsIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe}, claimsIdentity);
            return RedirectToLocal(returnUrl);
        }
    }
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}

(附注:我此时不需要登录外部用户。)

有什么建议么? -或者- 我是否应该回滚所有更改并等到 VS 2013 RTMd 为止?


更新、重构代码,使其更接近@Hao Kung 的原始回复。但是我仍然没有得到有效的用户身份。我认为我的 AuthenticationManager 分配不正确?

AuthenticationManger 现在定义为:

public IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }

SignInAsync 现在是一个单独的方法:

private async Task SignInAsync(EtdsUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var claimsIdentity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent}, claimsIdentity);
}

“SignOut”后,调试器显示:

AuthenticationManager.User.Identity
{System.Security.Principal.WindowsIdentity}
    [System.Security.Principal.WindowsIdentity]: {System.Security.Principal.WindowsIdentity}
    AuthenticationType: ""
    IsAuthenticated: false
    Name: ""

那么“claimsIdentity”就是:

claimsIdentity
{System.Security.Claims.ClaimsIdentity}
    Actor: null
    AuthenticationType: "ApplicationCookie"
    BootstrapContext: null
    Claims: {System.Security.Claims.ClaimsIdentity.get_Claims}
    IsAuthenticated: true
    Label: null
    Name: "alon"
    NameClaimType: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
    RoleClaimType: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"

“登录”不会改变任何内容:

AuthenticationManager.User.Identity
{System.Security.Principal.WindowsIdentity}
    [System.Security.Principal.WindowsIdentity]: {System.Security.Principal.WindowsIdentity}
    AuthenticationType: ""
    IsAuthenticated: false
    Name: ""

仍然没有身份验证,但似乎没有抛出任何错误。


正如 @Hao Kung 的回答,将 StartUp.Auth.cs 更改为:

var authOptions = new CookieAuthenticationOptions { ExpireTimeSpan = TimeSpan.FromHours(4.0)};
app.UseCookieAuthentication(authOptions);

To:

var authOptions = new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    ExpireTimeSpan = TimeSpan.FromHours(4.0)
}; ...

所以这就是 RTM 中登录的基本样子(代码复制自ASPNET 身份示例代码 https://github.com/rustd/AspnetIdentitySample):

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> 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);
    }

编辑:您需要在 Startup.Auth.cs 中进行以下更改:

        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 AspNet.Identity 通过 Asp.Net MVC5 RTM 位登录/验证用户? 的相关文章

随机推荐