asp.net core 3.x Identity

来源:https://www.cnblogs.com/jionsoft/archive/2020/02/26/12326788.html
-Advertisement-
Play Games

一、前言 這方面的資料很多,重覆的寫沒必要,但是最近一直在學習身份驗證和授權相關東東,為了成體系還是寫一篇,主要是從概念上理解identity系統。 參考:https://www.cnblogs.com/r01cn/p/5179506.html 二、概述 幾乎所有系統都包含用戶、角色、許可權、登錄、註 ...


一、前言

這方面的資料很多,重覆的寫沒必要,但是最近一直在學習身份驗證和授權相關東東,為了成體系還是寫一篇,主要是從概念上理解identity系統。

參考:https://www.cnblogs.com/r01cn/p/5179506.html

 

二、概述

幾乎所有系統都包含用戶、角色、許可權、登錄、註冊等等,以前我們通常是自己來實現,定義各種實體、以及對應的Repository、Service類,其實這些功能早在.net 2.0就已有實現,並且一直在進化,要麼是因為大家不瞭解,要麼是因為覺得擴展性不強,最終使用微軟提供的用戶管理的人不多,這裡就不扯以前的事了。現在的asp.net core延續了.net framework最後一次實現的Identity,暫且稱為“標識系統”吧。我的理解是它主要提供用戶管理、角色管理等功能,並且提供了相關的類與身份驗證系統結合,還包括持久化和UI,還提供了很多擴展點,當然預留了很多擴展點,也提供了預設實現,就使用起來。用還是不用瞭解之後再做決定也不遲。

身份驗證、授權、用戶/角色管理這三個系統是獨立的,只是授權依賴身份驗證,你要判斷某人能幹啥,至少得讓他先登錄吧。所以identity系統不是必須的,但是用它比自己實現更方便。另一個原因一些開源框架對於用戶、角色、許可權、登錄這些東西往往也是直接使用的微軟原生的,只是做了些許擴展和集成。

主要概念包括:

  • 用戶實體:IdentityUser,對應到用戶數據表
  • 用戶數據操作介面:UserStore,對用戶進行CRUD和其它功能的  與資料庫操作相關的功能
  • 用戶管理器:UserManager,對用戶進行CRUD和相關操作的業務邏輯類,
  • 登錄器:SignInManager提供登錄相關功能,實現identity系統和身份驗證系統的結合
  • 角色實體:類別用戶
  • 角色數據操作介面:類別用戶
  • 角色管理器:類比用戶

預設使用EF做資料庫相關操作,當然非常容易擴展。

 

三、IdentityUser

系統中通常有兩種用戶,

  • 一個是asp.net框架中的當前登錄用戶,也就是HttpContext.User,它是ClaimsPrincipal類型。它裡面相對來說屬性比較少,只包含用戶id和與授權判斷相關數據,比如角色
  • 一個是我們做用戶管理時的用戶實體。它包含完整的用戶信息

比如像“手機號”這個欄位在用戶實體里肯定是有的,但是沒必要放進當前登錄用戶,因為這個欄位不是每次請求都需要的。只要那些被平凡訪問的欄位放進當前登錄用戶才比較合適。

這個用戶就是用戶實體,對應到資料庫的用戶表。用下半身也能想到它大概包含哪些屬性:id、姓名、賬號、密碼、郵箱、性別、出生年月、民族、籍貫、地址、電話、巴拉巴拉.....

大概瞭解了啥是用戶,我們來看看它比較特殊的幾個點

3.1、繼承結構

 public class IdentityUser<TKey>    public class IdentityUser : IdentityUser<string> 

因為在設計identity系統時,不曉得將來的開發人員希望用什麼類型作為主鍵,所以定義成泛型。又由於大部分時候可能使用字元串(可能是對應guid),預設有個實現。

 

3.2、特殊欄位

NormalizedUserName:標準化的用戶名,預設是直接將UserName屬性轉換為大寫,主要可能用來方便提升查詢性能的。類似的還有Email與NormalizedEmail的關係
EmailConfirmed:是否已做了郵箱確認。我們註冊用戶時會向用戶發送一封郵件,用戶進入郵箱點擊郵件中的地址進行激活,此字典就是標識是否已激活了,類似的還有手機號確認PhoneNumberConfirmed
SecurityStamp:當在後臺修改用戶的跟安全相關的信息,比如修改了密碼,更新用戶到資料庫會自動更新此值,這樣用戶下次登錄時可以判斷此值變化了,要求用戶重新登錄。
ConcurrencyStamp:跟上面有點類似,不過主要是做併發衝突的,是針對整個用戶所有欄位更新的,比如有兩個現成都在修改同一個用戶,會比對此欄位是否另一個用戶也在修改,如果是則其中一個線程修改失敗
AccessFailedCount:登錄失敗次數,多次登錄失敗會鎖定的功能會用到此欄位。

 

3.3、額外概念

UserClaims:當用戶做第三方登錄(比如:微信、google)時,可能會獲取第三方中關於用戶的額外欄位,這些欄位就是存儲在用戶的Claim中的,所以這是一個一對多關係,一個用戶擁有多個第三方Claim
UserLogins:用戶第三方登錄,記錄某用戶綁定的第三方登錄的信息,比如openid啥的,所以也是一對多關係,一個用戶可能綁定多個第三方登錄
UserTokens:用戶登錄 發送手機驗證碼、或郵箱激活用的驗證碼之類的,也是一對多

 

3.x、如何擴展

定義IdentityUser子類、定義UserManager子類、定義RoleManager子類 ,由於這些還沒說,所以後面講吧

 

四、跟用戶相關的數據操作介面Store

 定義一堆介面來對用戶進行管理,這些功能都是跟資料庫操作相關的。看看這些介面是幹啥用的:

  • IUserLoginStore:管理用戶綁定第三方登錄的數據操作相關功能,比如獲取綁定的第三方登錄列表
  • IUserClaimStore:用戶做第三方登錄獲取的用戶的第三方賬號相關欄位值
  • IUserPasswordStore:專門針對用戶密碼的處理,比如設置獲取某用戶的密碼
  • IUserSecurityStampStore:參考
  • IUserEmailStore:針對用戶郵箱地址的處理
  • 略....

為毛要分開定義呢?還是那個話你可以對單獨的功能進行擴展。

可以看到整個繼承體系使用了很多泛型,目的是方便我們將來進行擴展,比如:我們將來可能使用int作為用戶的主鍵、也可能自定義一個用戶子類擴展更多欄位、也可能繼承Role實現更多屬性、也可能不使用EF,也可能使用EF,但是希望用自己的DBContext等等。。。。

為了將來擴展時儘量寫更少的代碼,所以實現了抽象類,也提供了預設子類,所以將來如果沒有特殊需求,對用戶管理的數據操作就完全不用自己寫,有特殊需求是簡單實現一個子類就ok拉,最最最複雜的情況我們才需要自己來實現這個介面

 

預設情況下使用UserStore這個類,它實現上面說的所有介面。

 

 

 

 

 

 

 

 

 

五、UserManager

用戶管理的業務邏輯類

內部使用IUserStore

最奇葩的是內部針對資料庫操作的上面說了分開介面定義的,但是在這個類內部使用時只註入了IUserStore,然後對特殊步驟的處理是直接拿這個強轉的。。所以將來擴展時我們必須重寫單獨那個方法,而不是只替換Store

AspNetUserManager<TUser>子類提供identity框架與asp.net框架結合的,主要就體現當前請求的CancellationToken的處理

 

待補充...........

六、SignInManager

用來結合identity系統和 身份驗證系統的,主要提供登錄、註銷相關功能。登錄又分為多種:賬號密碼登錄、第三方登錄、雙因素登錄

 

七、啟動配置

7.1、AddDefaultIdentity

  1. 註冊身份驗證需要的核心服務;設置預設身份驗證方案為“Identity.Appliction”,設置預設登錄使用的身份驗證方案為"Identity.External"。
  2. 註冊多個身份驗證驗證方案,其中就包含我們最常用的基於cookie的身份驗證方案以及第三方登錄、雙因素登錄等對應的身份驗證方案
  3. 註冊標識系統跟用戶管理相關的各種服務(這些服務主要在UserManager中被使用)
 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 }
AddDefaultIdentity

 

7.2、AddIdentityCookies

這裡對應上面的步驟2,上面源碼第8行

添加多個基於基於cookie的身份驗證方案,具體如下:

  1. 名稱=“Identity.Appliction”;  選項類型=CookieAuthenticationOptions;  身份驗證處理器類型=CookieAuthenticationHandler
  2. 名稱=Identity.External”;      選項類型=CookieAuthenticationOptions;  身份驗證處理器類型=CookieAuthenticationHandler
  3. 名稱=“Identity.TwoFactorRememberMe”;    選項類型=CookieAuthenticationOptions;  身份驗證處理器類型=CookieAuthenticationHandler
  4. 名稱=“Identity.TwoFactorUserId”;      選項類型=CookieAuthenticationOptions;  身份驗證處理器類型=CookieAuthenticationHandler

可以看到這4個身份驗證方案的身份驗證處理器和選項對象的類型都是一樣的,只是方案名稱不同,當然選項的值也不同。
第1個身份驗證方案是我們最常用的基於cookie的身份驗證,且它是預設身份驗證方案,意思是將來請求抵達時身份驗證中間件將嘗試從cookie中獲取用戶標識。
第2個身份驗證方案是跟第三方登錄相關的,第3、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     }
View Code

 

7.2.1、OptionsBuilder<TOptions>

若要完全掌握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>是一個通用類,所不同功能模塊的不同選項對象都可以使用它。

 

7.2.2、IdentityCookiesBuilder

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 }

 

7.2.3、如何為每種身份驗證方案設置選項

添加一個身份驗證方案通常需要:設置方案名、指定身份驗證處理器類型、配置身份驗證選項對象。根據上面的說明及源碼我們發現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>();
View Code

 另外如果我們不配置則這些選項對象將使用預設值,參考:asp.net core 3.x 身份驗證-2啟動階段的配置

 

7.3、AddIdentityCore

對應總步驟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 }
View Code

 

7.3.1、IdentityOptions

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 }
View Code

這個選項對象的賦值邏輯是通過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等多個組件都會使用到此選項對象。

 

7.3.2、IdentityBuilder

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 }
IdentityBuilder

 

八、基於RazorPages的UI

 

 

IdentityServiceCollectionExtensions

AddIdentity  ConfigureApplicationCookie ConfigureExternalCookie


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 最近django項目中使用到了定製後臺定時任務時報出“”及“ in crontab file, can't install”。經確認,根本原因是crontab文件中時間定義不正確導致的。簡單記錄一下這個,同時確認一下crontab中時間格式的規範,供參考。 1.具體報錯信息如下 ora10g@sec ...
  • 開發環境: Windows操作系統開發工具: Eclipse+Jdk+Tomcat+MySQL運行效果圖 源碼及原文鏈接:https://javadao.xyz/forum.php?mod=viewthread&tid=54 ...
  • 用scrapy只創建一個項目,創建多個spider,每個spider指定items,pipelines.啟動爬蟲時只寫一個啟動腳本就可以全部同時啟動。 本文代碼已上傳至github,鏈接在文未。 一,創建多個spider的scrapy項目 scrapy startproject mymultispi ...
  • WPF dotnet core 3.1 基於 `Microsoft.Extensions.Localization` 實現基本的多語言支持 ...
  • 在前一章已經學習過WPF動畫的第一條規則——每個動畫依賴於一個依賴項屬性。然而,還有另一個限制。為了實現屬性的動態化(換句話說,使用基於時間的方式改變屬性的值),需要有支持相應數據類型的動畫類。例如,Button.Width屬性使用雙精度數據類型。為實現屬性的動態化,需要使用DoubleAnimat ...
  • .NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect 繼上一篇 ".net core 3 web api jwt 一直 401" 為添加 所述的坑後, 本次為添加 ,又踩坑了。 自從 .NET Core 2.2 之後,CORS跨域配置代碼發 ...
  • 實體映射時,遇到複雜類型,可選擇下述方法處理: NotMapped,跳過映射 在複雜類型上聲明 [Owned],但僅限該複雜類型是全部由簡單值類型組成的 自定義序列化方法 示例: IPInfo使用了owned,對IPEndPoint使用自定義序列化,對VersionInfo使用JSON序列化 @@@... ...
  • 首先我們使用最簡單的模板案例,裡面有一個Counter計數器,你可以在創建模板中找到。 首先需要設置運行調試方式為IIS Express。這意味著,MAC可能不能使用調試。 然後開啟運行而不調試(Ctrl+F5) 按Shift + Alt + D,會出現一個新的頁面。 如果你想用Chrome調試,復 ...
一周排行
    -Advertisement-
    Play Games
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...