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

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

问题描述

道歉和预先感谢这个问题!我还是新的SO。

我一直使用MVC5,EF6一个Web应用程序,以及2013年VS

我花了一些时间升级一次发布的RC位。感谢所有伟大的帖子在那里:例如。 <一href=\"http://stackoverflow.com/questions/18727317/decoupling-microsoft-aspnet-identity?lq=1\">Decoupling Microsoft.AspNet.Identity * 和<一个href=\"http://stackoverflow.com/questions/18416915/updating-asp-net-mvc-from-5-0-0-beta2-to-5-0-0-rc1/18426574#184265\">Updating asp.net MVC从5.0.0-β2至5.0.0-RC1 !

在我无穷的智慧,我决定移动到@Hao功夫贴一下这里的RTM位:<一href=\"http://stackoverflow.com/questions/18793746/how-can-i-get-early-access-to-upcoming-asp-net-identity-changes\">How我可以提前获得即将到来的Asp.Net身份变化?。我想我会保存的麻烦,而不是落后的时候,我们终于得到了RTM版本太远。

这或者已是一场噩梦,还是我只是完全失去了一些东西(或两者),因为我无法弄清楚,一直在努力与RC1的东西基本任务。

虽然它看起来像我通过控制器登录用户(<一href=\"http://stackoverflow.com/questions/18801120/where-is-microsoft-aspnet-identity-owin-authenticationmanager-in-asp-net-identit\">Where是Microsoft.AspNet.Identity.Owin.AuthenticationManager在Asp.Net身份RTM版本?)......我的WindowsIdentity总是空的,而不是通过身份验证后,我打电话登入。用户和claimsIdentity对象已正确安装。

下面是操作方法我打电话(移动性局部变量的完整性):

  [HttpPost,使用AllowAnonymous,ValidateAntiForgeryToken]
公共虚拟异步任务&LT;&的ActionResult GT;登录(LoginViewModel型号,串RETURNURL)
{
    如果(ModelState.IsValid){
        变种的UserManager =新的UserManager&所述; EtdsUser&GT;(新UserStore&所述; EtdsUser&GT;(新EtdsContext()));
        VAR用户= userManager.Find(model.UserName,model.Password);
        如果(用户!= NULL){
            。VAR的AuthenticationManager = HttpContext.GetOwinContext()认证;
            authenticationManager.SignOut(新[] {DefaultAuthenticationTypes.ApplicationCookie,DefaultAuthenticationTypes.ExternalCookie,DefaultAuthenticationTypes.ExternalBearer});
            VAR claimsIdentity =等待userManager.CreateIdentityAsync(用户,DefaultAuthenticationTypes.ApplicationCookie);
            authenticationManager.SignIn(新AuthenticationProperties {IsPersistent = model.RememberMe},claimsIdentity);
            返回RedirectToLocal(RETURNURL);
        }
    }
    ModelState.AddModelError(,提供的用户名或密码不正确。);
    返回查看(模型);
}

(在一个侧面说明:我不需要登录,此时外部用户)

有什么建议?
-要么-
我应该回滚我所有的变化,只是等待,直到2013 VS是RTMd?


更新,重构code,使之更贴近@Hao功夫的原答复。不过我还是不带有效身份结束。我觉得我的AuthenticationManager是不是正确分配?

AuthenticationManger现在定义为:

 公共IAuthenticationManager的AuthenticationManager {{返回HttpContext.GetOwinContext()认证。 }}

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

 专用异步任务SignInAsync(EtdsUser用户,布尔isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    VAR claimsIdentity =等待_userManager.CreateIdentityAsync(用户,DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(新AuthenticationProperties {IsPersistent = isPersistent},claimsIdentity);
}

SignOut后,调试器显示:

  AuthenticationManager.User.Identity
{} System.Security.Principal.WindowsIdentity
    [System.Security.Principal.WindowsIdentity]:{} System.Security.Principal.WindowsIdentity
    AuthenticationType:
    IsAuthenticated:假的
    名称:

在claimsIdentity则为:

  claimsIdentity
{} System.Security.Claims.ClaimsIdentity
    演员:空
    AuthenticationType:ApplicationCookie
    BootstrapContext:空
    声明:{} System.Security.Claims.ClaimsIdentity.get_Claims
    IsAuthenticated:真
    标签:空
    产品名称:阿龙
    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:假的
    名称:

仍然没有认证,但似乎没有错误抛出。


作为回答@Hao功夫,改变StartUp.Auth.cs来自:

  VAR authOptions =新CookieAuthenticationOptions {ExpireTimeSpan = TimeSpan.FromHours(4.0)};
app.UseCookieAuthentication(authOptions);

要:

  VAR authOptions =新CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LOGINPATH =新PathString(/帐号/登录),
    ExpireTimeSpan = TimeSpan.FromHours(4.0)
}; ...


解决方案

因此​​,这里就是登录将基本上看起来像RTM(code从的 ASPNET身份样本code ):

  //
    // POST:/帐号/登录
    [HttpPost]
    [使用AllowAnonymous]
    [ValidateAntiForgeryToken]
    公共异步任务&LT;&的ActionResult GT;登录(LoginViewModel型号,串RETURNURL)
    {
        如果(ModelState.IsValid)
        {
            VAR用户=等待UserManager.FindAsync(model.UserName,model.Password);
            如果(用户!= NULL)
            {
                等待SignInAsync(用户,model.RememberMe);
                返回RedirectToLocal(RETURNURL);
            }
            其他
            {
                ModelState.AddModelError(,无效的用户名或密码。);
            }
        }        //如果我们走到这一步,事情失败了,重新显示形式
        返回查看(模型);
    }    私人异步任务SignInAsync(ApplicationUser用户,布尔isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        VAR身份=等待UserManager.CreateIdentityAsync(用户,DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(新AuthenticationProperties(){IsPersistent = isPersistent},身份);
    }

编辑:你需要在你的Startup.Auth.cs后续变化:

  app.UseCookieAuthentication(新CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LOGINPATH =新PathString(/帐号/登录)
        });

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 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 !

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.

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.

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.)

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


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 is now defined as:

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

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

After "SignOut", the debugger shows:

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

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.


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

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

解决方案

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

EDIT: 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天全站免登陆