日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用Identity Server 4建立Authorization Server (5)

發(fā)布時間:2023/12/4 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Identity Server 4建立Authorization Server (5) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

預(yù)備知識:?學(xué)習(xí)Identity Server 4的預(yù)備知識

第一部分:?使用Identity Server 4建立Authorization Server (1)

第二部分:?使用Identity Server 4建立Authorization Server (2)

第三部分:?使用Identity Server 4建立Authorization Server (3)

第四部分:?使用Identity Server 4建立Authorization Server (4)

之前的配置都是在內(nèi)存中, 下面將如何把這些數(shù)據(jù)存儲到Sql Server數(shù)據(jù)庫, 這樣更適合生產(chǎn)環(huán)境.

這部分基本完全參考官方文檔:

https://identityserver4.readthedocs.io/en/release/quickstarts/8_entity_framework.html

安裝Entity Framework相關(guān)的庫

為Authorization Server 添加 IdentityServer4.EntityFramework:

還需要安裝Microsoft.EntityFrameworkCore.SqlServer:

最后是Microsoft.EntityFrameworkCore.Tools:

使用它可以進(jìn)行遷移等操作.

然后使用命令行進(jìn)入Auth Server項目的目錄, 試一下dotnet ef命令:

很不幸, 沒找到dotnet ef命令. 這里需要手動修改AuthServer的項目文件, 右鍵點(diǎn)擊項目, 點(diǎn)擊Edit AuthServer.csproj.

這部分操作的官方文檔在這:?https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

我們需要添加這部分代碼:

<ItemGroup><DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /></ItemGroup>

然后回到命令行, 再執(zhí)行 dotnet ef:

這次好用了. 接下來就是add migrations了.

幸運(yùn)的是, 之前裝的庫里面有封裝好的model, 它們可以自動創(chuàng)建migration文件.

這里一共有兩個命令(migrations), 一個是為了IdentityServer的配置, 另一個是為了持久化授權(quán).

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb

運(yùn)行發(fā)現(xiàn)了問題, 這是因為我們還沒有配置AuthServer來使用數(shù)據(jù)庫.

添加appSettings.json, 并指定連接字符串:

{ ?"ConnectionStrings": { ? ?"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=AuthServer;Trusted_Connection=True;MultipleActiveResultSets=true"}, ?"Logging": { ? ?"IncludeScopes": false, ? ?"Debug": { ? ? ?"LogLevel": { ? ? ? ?"Default": "Warning"}}, ? ?"Console": { ? ? ?"LogLevel": { ? ? ? ?"Default": "Warning"}}} }

修改Startup.cs:

public class Startup{ ? ? ? ?public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }
? ? ? ?
public void ConfigureServices(IServiceCollection services){ ? ? ? ? ? ?var connectionString = Configuration.GetConnectionString("DefaultConnection");var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;services.AddIdentityServer() ? ? ? ? ? ? ? ?// .AddDeveloperSigningCredential().AddSigningCredential(new X509Certificate2(@"D:\Projects\test\socialnetwork.pfx", "Bx@steel")).AddTestUsers(InMemoryConfiguration.Users().ToList()) ? ? ? ? ? ? ? ?.AddConfigurationStore(options =>{options.ConfigureDbContext = builder =>builder.UseSqlServer(connectionString,sql => sql.MigrationsAssembly(migrationsAssembly));})// this adds the operational data from DB (codes, tokens, consents).AddOperationalStore(options =>{options.ConfigureDbContext = builder =>builder.UseSqlServer(connectionString,sql => sql.MigrationsAssembly(migrationsAssembly));// this enables automatic token cleanup. this is optional.options.EnableTokenCleanup = true;options.TokenCleanupInterval = 30;});services.AddMvc();}


首先獲取數(shù)據(jù)庫連接字符串, 然后添加兩部分配置, 一個是配置數(shù)據(jù)(clients, resources), 一個是操作數(shù)據(jù)(tokens, codes, consents同意).

再次運(yùn)行命令行:

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb

好用了.

看看生成的文件, 是有這兩部分:

看一下文件的內(nèi)容, 會發(fā)現(xiàn)有很多的Table.

下一步就是添加自動遷移, 暫且在StartUp里面找個位置新建個方法吧:

private void InitializeDatabase(IApplicationBuilder app){ ? ? ? ? ?
??
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()){serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate(); ? ? ? ?
? ? ? ?
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();context.Database.Migrate(); ? ? ? ? ? ? ? ?if (!context.Clients.Any()){ ? ? ? ? ? ? ? ?
? ?
foreach (var client in InMemoryConfiguration.Clients()){context.Clients.Add(client.ToEntity());}context.SaveChanges();} ? ? ? ? ? ? ?
?
if (!context.IdentityResources.Any()){ ? ? ? ? ? ? ? ?
? ?
foreach (var resource in InMemoryConfiguration.IdentityResources()){context.IdentityResources.Add(resource.ToEntity());}context.SaveChanges();} ? ? ? ? ? ? ?
?
if (!context.ApiResources.Any()){ ? ? ? ? ? ? ? ?
? ?
foreach (var resource in InMemoryConfiguration.ApiResources()){context.ApiResources.Add(resource.ToEntity());}context.SaveChanges();}}}

首先是分別對兩個context進(jìn)行遷移, 然后判斷是否這些表里是空的, 如果沒有數(shù)據(jù), 就把配置的內(nèi)存數(shù)據(jù)添加到數(shù)據(jù)庫里面.

別忘了在Configure方法調(diào)用:

public void Configure(IApplicationBuilder app, IHostingEnvironment env){ ? ? ? ? ? ?InitializeDatabase(app);app.UseDeveloperExceptionPage();app.UseIdentityServer();app.UseStaticFiles();app.UseMvcWithDefaultRoute();}

運(yùn)行項目, 重新操作一下登陸, 同意的過程, 依然好用.

看一下數(shù)據(jù)庫:

確實(shí)生成了很多表.

查看Clients表, 里面有三條數(shù)據(jù).

PersistedGrants里面也有一條數(shù)據(jù). 登陸時當(dāng)你同意請求許可的時候, 就會在這個表里面添加一條數(shù)據(jù).

把用戶存儲到數(shù)據(jù)庫

可以使用自定義的用戶表來存儲用戶數(shù)據(jù), 但是我要用的是asp.net core identity, 所以我就不講別的方式了.

不過首先, 需要重建個項目, 并且把之前講的所有內(nèi)容都操作一遍, 因為這里要使用asp.net core mvc 模板并使用Individual User Account的驗證方式:

?

建立好項目后, 需要把之前講的所有步驟操作一下, 然后安裝:?IdentityServer4.AspNetIdentity:

修改Startup, 大約成為這個樣子,?只看紅色部分即可:

namespace AuthorizationServer { ?
?
public class Startup{ ? ? ?

?
public Startup(IConfiguration configuration){Configuration = configuration;} ? ? ? ?public IConfiguration Configuration { get; } ? ? ? ?public void ConfigureServices(IServiceCollection services){ ? ? ? ? ?
??
var connectionString = Configuration.GetConnectionString("DefaultConnection"); ? ? ? ? ?
?
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(connectionString));services.AddIdentity<ApplicationUser, IdentityRole>(options =>{ ? ? ? ? ? ? ? ?// Password settingsoptions.Password.RequireDigit = false;options.Password.RequiredLength = 6;options.Password.RequireNonAlphanumeric = false;options.Password.RequireUppercase = false;options.Password.RequireLowercase = false;options.Password.RequiredUniqueChars = 2; ? ? ? ? ? ? ? ?// Lockout settingsoptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);options.Lockout.MaxFailedAccessAttempts = 5;options.Lockout.AllowedForNewUsers = true; ? ? ? ? ? ? ? ?// Signin settingsoptions.SignIn.RequireConfirmedEmail = false;options.SignIn.RequireConfirmedPhoneNumber = false; ? ? ? ? ? ? ? ?// User settingsoptions.User.RequireUniqueEmail = false; ? ? ? ? ? ? ? ?}).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();services.AddTransient<IEmailSender, EmailSender>();services.AddMvc();services.AddIdentityServer().AddDeveloperSigningCredential() ? ? ? ? ? ? ? ?// .AddSigningCredential(new X509Certificate2(@"D:\Projects\test\socialnetwork.pfx", "password")).AddConfigurationStore(options =>{options.ConfigureDbContext = builder =>builder.UseSqlServer(connectionString,sql => sql.MigrationsAssembly(migrationsAssembly));}).AddOperationalStore(options =>{options.ConfigureDbContext = builder =>builder.UseSqlServer(connectionString,sql => sql.MigrationsAssembly(migrationsAssembly));options.EnableTokenCleanup = true;options.TokenCleanupInterval = 30;}) ? ? ? ? ? ? ? ?.AddAspNetIdentity<ApplicationUser>();} ? ? ? ?
public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.InitializeDatabase(); ? ? ? ? ?
?
if (env.IsDevelopment()){app.UseDeveloperExceptionPage();app.UseBrowserLink();app.UseDatabaseErrorPage();} ? ? ? ?
? ?
else{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles(); ? ? ? ? ? ?app.UseIdentityServer();app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});}} }

注意在Configure方法里面不要使用app.UseAuthentication(), 因為app.UseIdentityServer()方法已經(jīng)包含了這個中間件. 然后使用命令行執(zhí)行:

dotnet ef database update

或者在Packge Manager Console執(zhí)行 update-database也行.

我照著官方文檔操作出現(xiàn)了一些問題, 有幾個重復(fù)的controller, 因為項目建立好之后有個HomeController和AccountController, 而使用Quickstart UI里面也有這兩個Controller.

所以我最后clone了官方的例子:??https://github.com/IdentityServer/IdentityServer4.Samples/tree/dev/Quickstarts/6_AspNetIdentity

修改了一下, 放到了我這個項目里:?https://github.com/solenovex/Learning-Identity-Server-4

其他

有的項目可能需要使用第三方登陸, 例如使用Google賬戶, 微軟賬戶, QQ等, 這部分請看官方文檔自行學(xué)習(xí)吧. 我要做的是企業(yè)內(nèi)部項目. 所以這塊先不研究了.

也有可能會使用Auth0, Stormpath這樣的OAuth Provider, Auth0我用過, 登陸有點(diǎn)慢, 但功能很強(qiáng)大. 這個也不講了, 他們的文檔寫的很好, 也給出了各種客戶端的代碼, 很容易集成.

Javascript 客戶端

這將是最后一部分.

手頭的項目有點(diǎn)急.??過幾天再寫這個.

原文地址:http://www.cnblogs.com/cgzl/p/7799567.html


.NET社區(qū)新聞,深度好文,歡迎訪問公眾號文章匯總 http://www.csharpkit.com

總結(jié)

以上是生活随笔為你收集整理的使用Identity Server 4建立Authorization Server (5)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。