簡體   English   中英

如何使用AspNet.Identity使用Asp.Net MVC5 RTM位登錄/驗證用戶?

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

道歉並提前感謝您提出這個問題! 我還是SO的新手。

我一直在使用MVC5,EF6和VS 2013開發Web應用程序。

一旦發布,我花了一些時間升級到RC位。 感謝所有偉大的帖子:例如。 解耦Microsoft.AspNet.Identity。*並將asp.net MVC從5.0.0-beta2更新到5.0.0-rc1

在我無限的智慧中,我決定轉向@Hao Kung在這里發布的RTM位: 我如何能夠及早訪問即將到來的Asp.Net Identity變化? 我認為當我們最終收到RTM版本時,我會省去麻煩並且不會太落后。

這可能是一場噩夢,或者我只是完全遺漏了某些東西(或兩者兼而有之),因為我無法弄清楚曾經使用RC1的基本任務。

雖然我似乎是通過控制器登錄用戶( Asp.Net Identity RTM版本中的Microsoft.AspNet.Identity.Owin.AuthenticationManager在哪里? )...我的WindowsIdentity始終為空,在我調用SignIn后未經過身份驗證。 正確填充了user和claimIdentity對象。

這是我調用的操作方法(為了完整性將屬性移動到局部變量):

[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: ""

那么“claimIdentity”就是:

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”不會改變任何東西:

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

至:

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

所以這里的RTM基本上是什么樣的(從ASPNET Identity示例代碼復制的代碼 ):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM