IdentityServer4 結合AspNet.Identity&數據庫配置Client數據

//ConfigureServices(IServiceCollection services) 設置

            var DbContextConnStr = Configuration.GetConnectionString("DefaultConnection");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext<ApplicationDbContext>(options => {
                options.UseSqlServer(DbContextConnStr, b => { b.MigrationsAssembly(migrationsAssembly); });
            });//設置SQLServer-dbCOntext

            //設置AspNet.Identity

           services.AddIdentity<ApplicationUser, IdentityRole>(IdentityOpts =>
            {
                // Password settings.
                IdentityOpts.Password.RequireDigit = true;
                IdentityOpts.Password.RequireLowercase = true;
                IdentityOpts.Password.RequireNonAlphanumeric = true;
                IdentityOpts.Password.RequireUppercase = true;
                IdentityOpts.Password.RequiredLength = 6;
                IdentityOpts.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                IdentityOpts.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                IdentityOpts.Lockout.MaxFailedAccessAttempts = 5;
                IdentityOpts.Lockout.AllowedForNewUsers = true;

                // User settings.
                IdentityOpts.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                IdentityOpts.User.RequireUniqueEmail = false;
            })
            .AddClaimsPrincipalFactory<CustomUserClaimsFactory<IdentityRole>>()//添加憑證支持IdentityRole到Claim
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

//認證服務器
            //http://localhost:5000/.well-known/openid-configuration
            services.AddIdentityServer(options =>
            {
                options.UserInteraction = new IdentityServer4.Configuration.UserInteractionOptions
                {
                    LoginUrl = "/Account/Login",//【必備】登錄地址  
                    LogoutUrl = "/Account/Logout",//【必備】退出地址 
                    //ConsentUrl = "/Consent",//【必備】允許授權同意頁面地址
                    //ErrorUrl = "/Account/Error", //【必備】錯誤頁面地址
                    LoginReturnUrlParameter = "ReturnUrl",//【必備】設置傳遞給登錄頁面的返回URL參數的名稱。默認爲returnUrl 
                    LogoutIdParameter = "logoutId", //【必備】設置傳遞給註銷頁面的註銷消息ID參數的名稱。缺省爲logoutId 
                    ConsentReturnUrlParameter = "ReturnUrl", //【必備】設置傳遞給同意頁面的返回URL參數的名稱。默認爲returnUrl
                    ErrorIdParameter = "errorId", //【必備】設置傳遞給錯誤頁面的錯誤消息ID參數的名稱。缺省爲errorId
                    CustomRedirectReturnUrlParameter = "ReturnUrl", //【必備】設置從授權端點傳遞給自定義重定向的返回URL參數的名稱。默認爲returnUrl
                    CookieMessageThreshold = 5, //【必備】由於瀏覽器對Cookie的大小有限制,設置Cookies數量的限制,有效的保證了瀏覽器打開多個選項卡,一旦超出了Cookies限制就會清除以前的Cookies值
                };
            })
            .AddDeveloperSigningCredential(filename: "tempkey.rsa")//開發環境證書

           // 添加配置數據到 from DB (clients, resources, CORS)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseSqlServer(DbContextConnStr, opts =>
                {
                    //MigrationsAssembly程序集必須設置一致
                    //dotnet ef migrations add InitConfigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/Configuration
                    opts.MigrationsAssembly(migrationsAssembly);//"MyIdentityServer"
                });
                options.DefaultSchema = "";
            })
            // 添加配置數據到 from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseSqlServer(DbContextConnStr, opts =>
                {
                    //MigrationsAssembly程序集必須設置一致
                    //dotnet ef migrations add InitPersistedGrant -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrant
                    opts.MigrationsAssembly(migrationsAssembly);//"MyIdentityServer"
                });
                options.DefaultSchema = "";
                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30; // interval in seconds, short for testing
            })
            .AddAspNetIdentity<ApplicationUser>();//添加AspNet.Identity支持


            ////自定義 客戶端資源密鑰驗證
            //services.AddTransient<IClientSecretValidator, ClientSecretValidatorExt>();
            ////自定義 Api資源密鑰驗證
            //services.AddTransient<IApiSecretValidator, MyApiSecretValidatorExt>();

            services.AddTransient<IProfileService, MyProfileServices>();//自定義 用戶權限頁信息
            services.AddTransient<IResourceOwnerPasswordValidator, ResourceOwnerPasswordExt>();//自定義資源所有者密碼模式認證

 

Configure(IApplicationBuilder app, IWebHostEnvironment env)設置

//認證方式
            //app.UseAuthentication();// UseAuthentication not needed -- UseIdentityServer add this
            app.UseIdentityServer();

 

 

發佈了40 篇原創文章 · 獲贊 9 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章