這方面的資料不少,重複的寫不必,可是最近一直在學習身份驗證和受權相關東東,爲了成體系仍是寫一篇,主要是從概念上理解identity系統。html
參考:http://www.javashuo.com/article/p-ncbfaojv-bh.html數據庫
幾乎全部系統都包含用戶、角色、權限、登陸、註冊等等,之前咱們一般是本身來實現,定義各類實體、以及對應的Repository、Service類,其實這些功能早在.net 2.0就已有實現,而且一直在進化,要麼是由於你們不瞭解,要麼是由於以爲擴展性不強,最終使用微軟提供的用戶管理的人很少,這裏就不扯之前的事了。如今的asp.net core延續了.net framework最後一次實現的Identity,暫且稱爲「標識系統」吧。個人理解是它主要提供用戶管理、角色管理等功能,而且提供了相關的類與身份驗證系統結合,還包括持久化和UI,還提供了不少擴展點,固然預留了不少擴展點,也提供了默認實現,就使用起來。用仍是不用瞭解以後再作決定也不遲。安全
身份驗證、受權、用戶/角色管理這三個系統是獨立的,只是受權依賴身份驗證,你要判斷某人能幹啥,至少得讓他先登陸吧。因此identity系統不是必須的,可是用它比本身實現更方便。另外一個緣由一些開源框架對於用戶、角色、權限、登陸這些東西每每也是直接使用的微軟原生的,只是作了些許擴展和集成。微信
主要概念包括:cookie
默認使用EF作數據庫相關操做,固然很是容易擴展。併發
系統中一般有兩種用戶,框架
好比像「手機號」這個字段在用戶實體裏確定是有的,可是不必放進當前登陸用戶,由於這個字段不是每次請求都須要的。只要那些被平凡訪問的字段放進當前登陸用戶才比較合適。asp.net
這個用戶就是用戶實體,對應到數據庫的用戶表。用下半身也能想到它大概包含哪些屬性:id、姓名、帳號、密碼、郵箱、性別、出生年月、民族、籍貫、地址、電話、巴拉巴拉.....ide
大概瞭解了啥是用戶,咱們來看看它比較特殊的幾個點post
public class IdentityUser<TKey> public class IdentityUser : IdentityUser<string>
由於在設計identity系統時,不曉得未來的開發人員但願用什麼類型做爲主鍵,因此定義成泛型。又因爲大部分時候可能使用字符串(多是對應guid),默認有個實現。
NormalizedUserName:標準化的用戶名,默認是直接將UserName屬性轉換爲大寫,主要可能用來方便提高查詢性能的。相似的還有Email與NormalizedEmail的關係
EmailConfirmed:是否已作了郵箱確認。咱們註冊用戶時會向用戶發送一封郵件,用戶進入郵箱點擊郵件中的地址進行激活,此字典就是標識是否已激活了,相似的還有手機號確認PhoneNumberConfirmed
SecurityStamp:當在後臺修改用戶的跟安全相關的信息,好比修改了密碼,更新用戶到數據庫會自動更新此值,這樣用戶下次登陸時能夠判斷此值變化了,要求用戶從新登陸。
ConcurrencyStamp:跟上面有點相似,不過主要是作併發衝突的,是針對整個用戶全部字段更新的,好比有兩個現成都在修改同一個用戶,會比對此字段是否另外一個用戶也在修改,若是是則其中一個線程修改失敗
AccessFailedCount:登陸失敗次數,屢次登陸失敗會鎖定的功能會用到此字段。
UserClaims:當用戶作第三方登陸(好比:微信、google)時,可能會獲取第三方中關於用戶的額外字段,這些字段就是存儲在用戶的Claim中的,因此這是一個一對多關係,一個用戶擁有多個第三方Claim
UserLogins:用戶第三方登陸,記錄某用戶綁定的第三方登陸的信息,好比openid啥的,因此也是一對多關係,一個用戶可能綁定多個第三方登陸
UserTokens:用戶登陸 發送手機驗證碼、或郵箱激活用的驗證碼之類的,也是一對多
定義IdentityUser子類、定義UserManager子類、定義RoleManager子類 ,因爲這些還沒說,因此後面講吧
定義一堆接口來對用戶進行管理,這些功能都是跟數據庫操做相關的。看看這些接口是幹啥用的:
爲毛要分開定義呢?仍是那個話你能夠對單獨的功能進行擴展。
能夠看到整個繼承體系使用了不少泛型,目的是方便咱們未來進行擴展,好比:咱們未來可能使用int做爲用戶的主鍵、也可能自定義一個用戶子類擴展更多字段、也可能繼承Role實現更多屬性、也可能不使用EF,也可能使用EF,可是但願用本身的DBContext等等。。。。
爲了未來擴展時儘可能寫更少的代碼,因此實現了抽象類,也提供了默認子類,因此未來若是沒有特殊需求,對用戶管理的數據操做就徹底不用本身寫,有特殊需求是簡單實現一個子類就ok拉,最最最複雜的狀況咱們才須要本身來實現這個接口
默認狀況下使用UserStore這個類,它實現上面說的全部接口。
用戶管理的業務邏輯類
內部使用IUserStore
最奇葩的是內部針對數據庫操做的上面說了分開接口定義的,可是在這個類內部使用時只注入了IUserStore,而後對特殊步驟的處理是直接拿這個強轉的。。因此未來擴展時咱們必須重寫單獨那個方法,而不是隻替換Store
AspNetUserManager<TUser>子類提供identity框架與asp.net框架結合的,主要就體現當前請求的CancellationToken的處理
待補充...........
用來結合identity系統和 身份驗證系統的,主要提供登陸、註銷相關功能。登陸又分爲多種:帳號密碼登陸、第三方登陸、雙因素登陸
1 1public static IdentityBuilder AddDefaultIdentity<TUser>(this IServiceCollection services, Action<IdentityOptions> configureOptions) where TUser : class 2 { 3 services.AddAuthentication(o => 4 { 5 o.DefaultScheme = IdentityConstants.ApplicationScheme; 6 o.DefaultSignInScheme = IdentityConstants.ExternalScheme; 7 }) 8 .AddIdentityCookies(o => { }); 9 10 return services.AddIdentityCore<TUser>(o => 11 { 12 o.Stores.MaxLengthForKeys = 128; 13 configureOptions?.Invoke(o); 14 }) 15 .AddDefaultUI() 16 .AddDefaultTokenProviders(); 17 }
這裏對應上面的步驟2,上面源碼第8行
添加多個基於基於cookie的身份驗證方案,具體以下:
能夠看到這4個身份驗證方案的身份驗證處理器和選項對象的類型都是同樣的,只是方案名稱不一樣,固然選項的值也不一樣。
第1個身份驗證方案是咱們最經常使用的基於cookie的身份驗證,且它是默認身份驗證方案,意思是未來請求抵達時身份驗證中間件將嘗試從cookie中獲取用戶標識。
第2個身份驗證方案是跟第三方登陸相關的,第三、4個是跟雙因素登陸(估計相似手機驗證碼登陸)相關的,後期再說。
1 public static class IdentityCookieAuthenticationBuilderExtensions 2 { 3 public static IdentityCookiesBuilder AddIdentityCookies(this AuthenticationBuilder builder) 4 => builder.AddIdentityCookies(o => { }); 5 6 public static IdentityCookiesBuilder AddIdentityCookies(this AuthenticationBuilder builder, Action<IdentityCookiesBuilder> configureCookies) 7 { 8 var cookieBuilder = new IdentityCookiesBuilder(); 9 cookieBuilder.ApplicationCookie = builder.AddApplicationCookie(); 10 cookieBuilder.ExternalCookie = builder.AddExternalCookie(); 11 cookieBuilder.TwoFactorRememberMeCookie = builder.AddTwoFactorRememberMeCookie(); 12 cookieBuilder.TwoFactorUserIdCookie = builder.AddTwoFactorUserIdCookie(); 13 configureCookies?.Invoke(cookieBuilder); 14 return cookieBuilder; 15 } 16 17 public static OptionsBuilder<CookieAuthenticationOptions> AddApplicationCookie(this AuthenticationBuilder builder) 18 { 19 builder.AddCookie(IdentityConstants.ApplicationScheme, o => 20 { 21 o.LoginPath = new PathString("/Account/Login"); 22 o.Events = new CookieAuthenticationEvents 23 { 24 OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync 25 }; 26 }); 27 return new OptionsBuilder<CookieAuthenticationOptions>(builder.Services, IdentityConstants.ApplicationScheme); 28 } 29 30 public static OptionsBuilder<CookieAuthenticationOptions> AddExternalCookie(this AuthenticationBuilder builder) 31 { 32 builder.AddCookie(IdentityConstants.ExternalScheme, o => 33 { 34 o.Cookie.Name = IdentityConstants.ExternalScheme; 35 o.ExpireTimeSpan = TimeSpan.FromMinutes(5); 36 }); 37 return new OptionsBuilder<CookieAuthenticationOptions>(builder.Services, IdentityConstants.ExternalScheme); 38 } 39 40 public static OptionsBuilder<CookieAuthenticationOptions> AddTwoFactorRememberMeCookie(this AuthenticationBuilder builder) 41 { 42 builder.AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o => o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme); 43 return new OptionsBuilder<CookieAuthenticationOptions>(builder.Services, IdentityConstants.TwoFactorRememberMeScheme); 44 } 45 46 public static OptionsBuilder<CookieAuthenticationOptions> AddTwoFactorUserIdCookie(this AuthenticationBuilder builder) 47 { 48 builder.AddCookie(IdentityConstants.TwoFactorUserIdScheme, o => 49 { 50 o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme; 51 o.ExpireTimeSpan = TimeSpan.FromMinutes(5); 52 }); 53 return new OptionsBuilder<CookieAuthenticationOptions>(builder.Services, IdentityConstants.TwoFactorUserIdScheme); 54 } 55 }
若要徹底掌握asp.net core的選項模型請參考:https://www.cnblogs.com/artech/p/inside-asp-net-core-06-01.html
一般咱們定義同樣選項模型的賦值邏輯是在Startup中經過以下方式來定義
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.Configure<CookiePolicyOptions>(opt => { 4 //選項對象的賦值邏輯 5 //opt... 6 }); 7 services.PostConfigure<CookiePolicyOptions>(opt => { 8 //選項對象的覆蓋邏輯 9 //opt... 10 });
若咱們開發一個功能組件,能夠調用方一個機會能夠對咱們組件進行配置,一般咱們提供一個選項對象,調用方能夠經過上面的方式來定義選項對象的賦值邏輯,咱們組件內部經過依賴注入直接使用這個選項對象就能夠了。更好的方式是咱們的組件向外暴露一個OptionsBuilder<TOptions>,其中TOptions就是選項類型。下面直接經過如何使用它來理解它的用途。假設咱們的組件向調用方暴露一個OptionsBuilder<MyModule>
1 var optBuilder = //咱們的模塊提供一個擴展方法返回OptionsBuilder<MyModuleOptions> 2 optBuilder.Configre(opt=>{ 3 opt.XXXX = xxx..; 4 //..... 5 });
固然也提供了PostConfigure,能夠發現返回的對象已經指明瞭選項對象的類型,所以後續的調用無需提供泛型參數,因此調用方會以爲這種方式更簡單;並且此Builder對象是專門針對咱們的模塊的選項對象,因此更具相關性。
OptionsBuilder<TOptions>是一個通用類,所不一樣功能模塊的不一樣選項對象均可以使用它。
1 public class IdentityCookiesBuilder 2 { 3 public OptionsBuilder<CookieAuthenticationOptions> ApplicationCookie { get; set; } 4 public OptionsBuilder<CookieAuthenticationOptions> ExternalCookie { get; set; } 5 public OptionsBuilder<CookieAuthenticationOptions> TwoFactorRememberMeCookie { get; set; } 6 public OptionsBuilder<CookieAuthenticationOptions> TwoFactorUserIdCookie { get; set; } 7 }
添加一個身份驗證方案一般須要:設置方案名、指定身份驗證處理器類型、配置身份驗證選項對象。根據上面的說明及源碼咱們發現AddDefaultIdentity中的AddIdentityCookies只是添加了4個身份驗證方案,分別設置了名稱,並由於AddCookie,因此都是添加的CookieAuthenticationHandler做爲身份驗證處理器的,那麼選項對象如何配置呢?其實就是調用AddIdentityCookies丟入一個委託進行配置的,只是AddDefaultIdentity中沒有給了一個空委託 .AddIdentityCookies(o => { }); ,徹底能夠經過相似以下代碼進行配置
1 .AddIdentityCookies(o => { 2 //配置默認身份驗證的選項 3 o.ApplicationCookie.Configre(opt=>{} 4 opt.....//配置 5 ); 6 //配置第三方登陸的相關選項 7 o.ExternalCookie.Configre(opt=>{} 8 opt.....//配置 9 ); 10 ....雙因素登陸... 11 });
遺憾的是AddDefaultIdentity沒有給我機會來配置這些選項。可能之因此叫AddDefault的緣由,其實安全能夠在參數中多提供一個委託,內部作下回調,從而容許咱們能夠進行配置。話說回來咱們徹底能夠不使用AddDefaultIdentity,而是手動去Startup中註冊相關服務並配置選項。相似下面這樣
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddDbContext<ApplicationDbContext>(options => 4 options.UseSqlServer( 5 Configuration.GetConnectionString("DefaultConnection"))); 6 7 services.AddAuthentication(o => 8 { 9 o.DefaultScheme = IdentityConstants.ApplicationScheme; 10 o.DefaultSignInScheme = IdentityConstants.ExternalScheme; 11 }).AddApplicationCookie().Configure(opt=> { 12 //配置此方案的選項 13 }); 14 services.AddIdentityCore<IdentityUser>(o => 15 { 16 o.Stores.MaxLengthForKeys = 128; 17 }) 18 .AddDefaultUI() 19 .AddDefaultTokenProviders() 20 .AddEntityFrameworkStores<ApplicationDbContext>();
另外若是咱們不配置則這些選項對象將使用默認值,參考:asp.net core 3.x 身份驗證-2啓動階段的配置
對應總步驟3,註冊Identity(標識系統)跟用戶管理相關的服務。具體參考下面的源碼:
1 public static IdentityBuilder AddIdentityCore<TUser>(this IServiceCollection services, Action<IdentityOptions> setupAction) where TUser : class 2 { 3 // Services identity depends on 4 services.AddOptions().AddLogging(); 5 6 // Services used by identity 7 services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>(); 8 services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>(); 9 services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>(); 10 services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>(); 11 services.TryAddScoped<IUserConfirmation<TUser>, DefaultUserConfirmation<TUser>>(); 12 // No interface for the error describer so we can add errors without rev'ing the interface 13 services.TryAddScoped<IdentityErrorDescriber>(); 14 services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser>>(); 15 services.TryAddScoped<UserManager<TUser>>(); 16 if (setupAction != null) 17 { 18 services.Configure(setupAction); 19 } 20 return new IdentityBuilder(typeof(TUser), services); 21 }
Identity系統中會用到各類配置選項就是經過它來提供的,它至關於一個選項對象的容器,裏面包含各類子選項對象,看看源碼
1 public class IdentityOptions 2 { 3 public ClaimsIdentityOptions ClaimsIdentity { get; set; } = new ClaimsIdentityOptions(); 4 public UserOptions User { get; set; } = new UserOptions(); 5 public PasswordOptions Password { get; set; } = new PasswordOptions(); 6 public LockoutOptions Lockout { get; set; } = new LockoutOptions(); 7 public SignInOptions SignIn { get; set; } = new SignInOptions(); 8 public TokenOptions Tokens { get; set; } = new TokenOptions(); 9 public StoreOptions Stores { get; set; } = new StoreOptions(); 10 }
這個選項對象的賦值邏輯是經過AddDefaultIdentity的委託參數傳進來的,這意味着咱們配置時能夠經過以下方式來配置Identity系統的選項:
1 services.AddDefaultIdentity<IdentityUser>(options => 2 { 3 options.SignIn.RequireConfirmedAccount = true; 4 options.Password.RequiredLength = 9;//密碼相關配置 5 options.SignIn.RequireConfirmedEmail = true;//登陸相關配置 6 //其它相關配置.... 7 }) 8 .AddEntityFrameworkStores<ApplicationDbContext>();
在登陸管理器SignInManager、UserManager等多個組件都會使用到此選項對象。
AddIdentityCore方法只是註冊與用戶管理相關服務,這是一種最小注冊,若是還但願使用更多Identity系統提供的功能還須要註冊其它相關服務,註冊這些服務的方法就定義在IdentityBuilder,其實徹底可使用services進行註冊,只是使用IdentityBuilder更簡單,也跟具相關性,由於這些註冊方法都是跟Identity系統相關的。
AddIdentityCore的返回類型是IdentityBuilder、也做爲AddDefaultIdentity的最終返回對象。所以咱們能夠在調用AddDefaultIdentity後繼續作其它服務的配置,例如在Startup中這樣:
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoleManager<RoleManager<IdentityUser>>()//註冊角色管理器 .AddEntityFrameworkStores<ApplicationDbContext>();//註冊基於ef的數據操做類
IdentityBuilder完整源碼:
1 public class IdentityBuilder 2 { 3 public IdentityBuilder(Type user, IServiceCollection services) 4 { 5 UserType = user; 6 Services = services; 7 } 8 public IdentityBuilder(Type user, Type role, IServiceCollection services) : this(user, services) 9 => RoleType = role; 10 public Type UserType { get; private set; } 11 public Type RoleType { get; private set; } 12 public IServiceCollection Services { get; private set; } 13 private IdentityBuilder AddScoped(Type serviceType, Type concreteType) 14 { 15 Services.AddScoped(serviceType, concreteType); 16 return this; 17 } 18 public virtual IdentityBuilder AddUserValidator<TValidator>() where TValidator : class 19 => AddScoped(typeof(IUserValidator<>).MakeGenericType(UserType), typeof(TValidator)); 20 public virtual IdentityBuilder AddClaimsPrincipalFactory<TFactory>() where TFactory : class 21 => AddScoped(typeof(IUserClaimsPrincipalFactory<>).MakeGenericType(UserType), typeof(TFactory)); 22 public virtual IdentityBuilder AddErrorDescriber<TDescriber>() where TDescriber : IdentityErrorDescriber 23 { 24 Services.AddScoped<IdentityErrorDescriber, TDescriber>(); 25 return this; 26 } 27 public virtual IdentityBuilder AddPasswordValidator<TValidator>() where TValidator : class 28 => AddScoped(typeof(IPasswordValidator<>).MakeGenericType(UserType), typeof(TValidator)); 29 public virtual IdentityBuilder AddUserStore<TStore>() where TStore : class 30 => AddScoped(typeof(IUserStore<>).MakeGenericType(UserType), typeof(TStore)); 31 public virtual IdentityBuilder AddTokenProvider<TProvider>(string providerName) where TProvider : class 32 => AddTokenProvider(providerName, typeof(TProvider)); 33 public virtual IdentityBuilder AddTokenProvider(string providerName, Type provider) 34 { 35 if (!typeof(IUserTwoFactorTokenProvider<>).MakeGenericType(UserType).GetTypeInfo().IsAssignableFrom(provider.GetTypeInfo())) 36 { 37 throw new InvalidOperationException(Resources.FormatInvalidManagerType(provider.Name, "IUserTwoFactorTokenProvider", UserType.Name)); 38 } 39 Services.Configure<IdentityOptions>(options => 40 { 41 options.Tokens.ProviderMap[providerName] = new TokenProviderDescriptor(provider); 42 }); 43 Services.AddTransient(provider); 44 return this; 45 } 46 public virtual IdentityBuilder AddUserManager<TUserManager>() where TUserManager : class 47 { 48 var userManagerType = typeof(UserManager<>).MakeGenericType(UserType); 49 var customType = typeof(TUserManager); 50 if (!userManagerType.GetTypeInfo().IsAssignableFrom(customType.GetTypeInfo())) 51 { 52 throw new InvalidOperationException(Resources.FormatInvalidManagerType(customType.Name, "UserManager", UserType.Name)); 53 } 54 if (userManagerType != customType) 55 { 56 Services.AddScoped(customType, services => services.GetRequiredService(userManagerType)); 57 } 58 return AddScoped(userManagerType, customType); 59 } 60 public virtual IdentityBuilder AddRoles<TRole>() where TRole : class 61 { 62 RoleType = typeof(TRole); 63 AddRoleValidator<RoleValidator<TRole>>(); 64 Services.TryAddScoped<RoleManager<TRole>>(); 65 Services.AddScoped(typeof(IUserClaimsPrincipalFactory<>).MakeGenericType(UserType), typeof(UserClaimsPrincipalFactory<,>).MakeGenericType(UserType, RoleType)); 66 return this; 67 } 68 public virtual IdentityBuilder AddRoleValidator<TRole>() where TRole : class 69 { 70 if (RoleType == null) 71 { 72 throw new InvalidOperationException(Resources.NoRoleType); 73 } 74 return AddScoped(typeof(IRoleValidator<>).MakeGenericType(RoleType), typeof(TRole)); 75 } 76 public virtual IdentityBuilder AddPersonalDataProtection<TProtector, TKeyRing>() 77 where TProtector : class,ILookupProtector 78 where TKeyRing : class, ILookupProtectorKeyRing 79 { 80 Services.AddSingleton<IPersonalDataProtector, DefaultPersonalDataProtector>(); 81 Services.AddSingleton<ILookupProtector, TProtector>(); 82 Services.AddSingleton<ILookupProtectorKeyRing, TKeyRing>(); 83 return this; 84 } 85 public virtual IdentityBuilder AddRoleStore<TStore>() where TStore : class 86 { 87 if (RoleType == null) 88 { 89 throw new InvalidOperationException(Resources.NoRoleType); 90 } 91 return AddScoped(typeof(IRoleStore<>).MakeGenericType(RoleType), typeof(TStore)); 92 } 93 public virtual IdentityBuilder AddRoleManager<TRoleManager>() where TRoleManager : class 94 { 95 if (RoleType == null) 96 { 97 throw new InvalidOperationException(Resources.NoRoleType); 98 } 99 var managerType = typeof(RoleManager<>).MakeGenericType(RoleType); 100 var customType = typeof(TRoleManager); 101 if (!managerType.GetTypeInfo().IsAssignableFrom(customType.GetTypeInfo())) 102 { 103 throw new InvalidOperationException(Resources.FormatInvalidManagerType(customType.Name, "RoleManager", RoleType.Name)); 104 } 105 if (managerType != customType) 106 { 107 Services.AddScoped(typeof(TRoleManager), services => services.GetRequiredService(managerType)); 108 } 109 return AddScoped(managerType, typeof(TRoleManager)); 110 } 111 }
IdentityServiceCollectionExtensions
AddIdentity ConfigureApplicationCookie ConfigureExternalCookie