ASP.NET Identity 是4.5中引入的,支持Clamis(聲明)式樣登錄【即認證和受權分開模式】,結合owin能夠實現cookie加密等功能。cookie
1.ASP.NET Identity架構框架說明架構
最上面是集成實現中間(identity.entityframwork---它是實現了用戶數據的存儲方式,這層是微軟本身實現的基於EF存儲的實現層。能夠直接幾重identity.core重寫以實現不一樣存儲方式)。
其中IuserStore UserStore是實現對用戶對象在存儲的一些數據操做方法實現,好比密碼驗證方法或者查找用戶方法等。
identityUser繼承自底層IUser,能夠擴展用戶的字段數據等。
mvc
最終會把IUserStore做爲參數實例化UserManager來作用戶的相關業務邏輯操做。app
二、OWIN是微軟定義了一套替代IIS管道處理的東西,這樣 request和response上下文content的操做和appapliction等操做都託管給了Owin處理。框架
結合實現聲明式(Claims)登錄爲例子解釋owin,下面是登錄代碼ide
// 1. 利用ASP.NET Identity獲取用戶對象 var user = await UserManager.FindAsync("UserName", "Password"); // 2. 利用ASP.NET Identity獲取ClaimsIdentity(identity 對象,包含用戶的基本信息 ) var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // 3. 將上面拿到的identity對象利用OWIN的管道處理方法登陸,加密寫入讀取coocie和處理 及管理ClaimsPrincipal對象(是2的封裝,這個對象是賦值給http--> crrentUser) AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
結合上面和下面圖片代碼(引用園友的一段代碼說明),基於聲明的身份驗證核心部分就是 var identity=new ClaimsIdentity(claims,"stringType"),聲明這個後,當前用戶上下文的IsAutheiticated將會被賦值爲true。post
OWIN的開源實現是Katana,實現了四個網站
以登錄爲例,實現owin必需要有個聲明入口starup(新建mvc後能夠在appstart文件夾中看到)
ui
public partial class Startup { public void ConfigureAuth(IAppBuilder app) { // 配置Middleware 組件選項,中間件是爲了處理不一樣的業務例以下面的CookieAuthenticationMiddleware,能夠參考他來自定義中間件,能夠參考開源的owin--catana代碼
//這裏是處理使用coocie登錄的中間件,是iappbuilder的擴展方法 app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), CookieSecure = CookieSecureOption.Never, }); } }
這個是上門中間件擴展方法的實現this
public static IAppBuilder UseCookieAuthentication(this IAppBuilder app, CookieAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException("app"); } app.Use(typeof(CookieAuthenticationMiddleware), app, options); //將組件註冊進owin管道,--CookieAuthenticationMiddleware--組件是操做加密coocie的
app.UseStageMarker(PipelineStage.Authenticate); // 而後結合例如IIS(owin的HOST)的某個階段執行該組件,這裏是認證階段,還有七八種其餘的例如post數據階段等 return app; }