如何使用 AspNet.Identity 使用 Asp.Net MVC5 RTM 位登录/验证用户? [英] How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity?

查看:27
本文介绍了如何使用 AspNet.Identity 使用 Asp.Net MVC5 RTM 位登录/验证用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉并提前感谢您提出这个问题!我还是个新手.

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

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

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

我花了一些时间升级到发布后的 RC 位.感谢那里的所有精彩帖子:例如.分离 Microsoft.AspNet.Identity.*从 5.0 更新 asp.net MVC.0-beta2 到 5.0.0-rc1 !

I spent some time upgrading to the RC bits once released. Thanks to all the great posts out there: eg. Decoupling Microsoft.AspNet.Identity.* and Updating asp.net MVC from 5.0.0-beta2 to 5.0.0-rc1 !

以我无限的智慧,我决定转向@Hao Kung 在这里发布的 RTM 位:如何提前访问即将到来的 Asp.Net Identity 更改?.我想当我们最终收到 RTM 版本时,我会省去麻烦并且不会落后太多.

In my infinite wisdom, I decided to move to the RTM bits that @Hao Kung posted about here: How can I get early access to upcoming Asp.Net Identity changes?. I figured I would save the trouble and not be too far behind when we finally receive the RTM build.

这要么是一场噩梦,要么是我完全遗漏了一些东西(或两者兼有),因为我无法弄清楚使用 RC1 的东西的基本任务.

This has either been a nightmare, or I am just completely missing something (or both) as I can not figure out basic tasks that had been working with the RC1 stuff.

虽然我似乎是通过控制器登录用户 (Asp.Net Identity RTM 版本中的 Microsoft.AspNet.Identity.Owin.AuthenticationManager 在哪里?)...我的 WindowsIdentity 始终为空,并且在我调用 SignIn 后未通过身份验证.用户和 claimIdentity 对象已正确填充.

While it seems like I am logging the user in via the controller (Where is Microsoft.AspNet.Identity.Owin.AuthenticationManager in Asp.Net Identity RTM version?) ... my WindowsIdentity is always empty and not authenticated after I call SignIn. The user and claimsIdentity object are correctly populated.

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

Here is the action method I am calling (moved properties to local variables for completeness):

[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);
}

(附带说明:我此时不需要登录外部用户.)

(On a side note: I do not need to log in external users at this time.)

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

Any suggestions? -or- Should I roll back all my changes and just wait until VS 2013 is RTMd?

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

Update, refactored code to make it closer to @Hao Kung's original reply. However I still do not end up with a valid user identity. I think my AuthenticationManager is not assigned correctly?

AuthenticationManger 现在定义为:

AuthenticationManger is now defined as:

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

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

SignInAsync is now a separate method:

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"后,调试器显示:

After "SignOut", the debugger shows:

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

claimsIdentity"是:

The "claimsIdentity" is then:

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"

登录"不会改变任何东西:

"SignIn" does not change anything:

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

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

Still no Authentication, but seems that no errors are thrown.

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

As answered by @Hao Kung, changed StartUp.Auth.cs from:

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

致:

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

推荐答案

这里是登录在 RTM 中的基本样子(代码复制自 ASPNET 身份示例代码):

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<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 中进行以下更改:

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

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

这篇关于如何使用 AspNet.Identity 使用 Asp.Net MVC5 RTM 位登录/验证用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆