主頁 > .NET開發 > asp.net core 3.x Identity

asp.net core 3.x Identity

2020-09-17 03:07:15 .NET開發

一、前言

這方面的資料很多,重復的寫沒必要,但是最近一直在學習身份驗證和授權相關東東,為了成體系還是寫一篇,主要是從概念上理解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

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/61677.html

標籤:.NET Core

上一篇:dotnetcore3.1 WPF 中使用依賴注入

下一篇:vb.net做了一個程式之后,把專案檔案發給其他人,出現下面的提示,請問是什么原因呢?怎么修改?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more