下面是我提出的解決方案。它仍然不是我想要的那樣清楚,它使用cookies,所以任何補充都是值得歡迎的。
首先,我必須安裝Microsoft.AspNet.Identity.Owin包,並且其所有的依賴。
然後我註冊了我的身份驗證如下:然後
private void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
這種方法被稱爲Startup.cs文件的配置方法。
爲了與認證工作,需要IAuthenticationManager的一個實例。我把它注射到我的控制器,並使用Ninject來解決依賴
kernel.Bind<IAuthenticationManager>().ToMethod(_ => HttpContext.Current.GetOwinContext().Authentication).InRequestScope();
下面是該用戶被重定向時AUTH需要(在ConfigureAuth方法由於LOGINPATH)到賬戶控制器的登錄方法:
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = authenticationService.AuthenticateUser(model.Login);
IdentitySignIn(user.Id, user.Login);
return RedirectToAction("Index", "Home");
}
AuthenticationService是我自己的類,它與數據庫通信並執行登錄來創建或返回用戶。
IdentitySignIn聲明如下:
private void IdentitySignIn(int userId, string userLogin)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.PrimarySid, userId.ToString()));
claims.Add(new Claim(ClaimTypes.Name, userLogin));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties()
{
ExpiresUtc = DateTime.UtcNow.AddDays(200),
IsPersistent = true
}, identity);
}
此方法創建具有適當信息的cookie。但有一件事。當我檢查cookie過期日期時,它不是當前日期加上200天,這是有點尷尬。
SignOut方法很簡單:
public void IdentitySignout()
{
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}
所以,User.Identity現在與Identity.Name屬性SignalR樞紐訪問。
要做的事:通過類似User.Identity.Id的方式訪問Id屬性也不錯。據我所知,它需要實施自定義校長。 我還在考慮使用Cookie來實現某種會話,以在客戶端存儲會話ID,儘管它肯定比使用Identity需要更多的時間。
增加: 爲了獲得用戶ID,一個可能使用IdentityExtensions的擴展方法:
(在輪轂內)
Context.User.Identity.GetUserId()
爲了這個工作,索賠用戶ID的值應該具有ClaimTypes.NameIdentifier類型。
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, userId.ToString()));
claims.Add(new Claim(ClaimTypes.Name, userLogin));
更新2:
以下是關於這個問題,極大地幫助了我一些額外的鏈接。我不包含MS指南的鏈接,因爲它們很容易找到。
http://leastprivilege.com/2015/07/21/the-state-of-security-in-asp-net-5-and-mvc-6-claims-authentication/
http://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application