预备知识: http://www.cnblogs.com/cgzl/p/7746496.html

第一部分: http://www.cnblogs.com/cgzl/p/7780559.html

第二部分: http://www.cnblogs.com/cgzl/p/7788636.html

第三部分: http://www.cnblogs.com/cgzl/p/7793241.html

第四部分: http://www.cnblogs.com/cgzl/p/7795121.html

之前的配置都是在内存中, 下面将如何把这些数据存储到Sql Server数据库, 这样更适合生产环境.

这部分基本完全参考官方文档:

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

安装Entity Framework相关的库

为Authorization Server 添加 IdentityServer4.EntityFramework:

还需要安装Microsoft.EntityFrameworkCore.SqlServer:

最后是Microsoft.EntityFrameworkCore.Tools:

使用它可以进行迁移等操作.

然后使用命令行进入Auth Server项目的目录, 试一下dotnet ef命令:

很不幸, 没找到dotnet ef命令. 这里需要手动修改AuthServer的项目文件, 右键点击项目, 点击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>

然后回到命令行, 再执行 dotnet ef:

这次好用了. 接下来就是add migrations了.

幸运的是, 之前装的库里面有封装好的model, 它们可以自动创建migration文件.

这里一共有两个命令(migrations), 一个是为了IdentityServer的配置, 另一个是为了持久化授权.

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

运行发现了问题, 这是因为我们还没有配置AuthServer来使用数据库.

添加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();
}

首先获取数据库连接字符串, 然后添加两部分配置, 一个是配置数据(clients, resources), 一个是操作数据(tokens, codes, consents同意).

再次运行命令行:

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

好用了.

看看生成的文件, 是有这两部分:

看一下文件的内容, 会发现有很多的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进行迁移, 然后判断是否这些表里是空的, 如果没有数据, 就把配置的内存数据添加到数据库里面.

别忘了在Configure方法调用:

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

运行项目, 重新操作一下登陆, 同意的过程, 依然好用.

看一下数据库:

确实生成了很多表.

查看Clients表, 里面有三条数据.

PersistedGrants里面也有一条数据. 登陆时当你同意请求许可的时候, 就会在这个表里面添加一条数据.

把用户存储到数据库

可以使用自定义的用户表来存储用户数据, 但是我要用的是asp.net core identity, 所以我就不讲别的方式了.

不过首先, 需要重建个项目, 并且把之前讲的所有内容都操作一遍, 因为这里要使用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 settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = ;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = ;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();
options.Lockout.MaxFailedAccessAttempts = ;
options.Lockout.AllowedForNewUsers = true;
// Signin settings
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
// User settings
options.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 = ;
})
.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()方法已经包含了这个中间件. 然后使用命令行执行:

dotnet ef database update

或者在Packge Manager Console执行 update-database也行.

我照着官方文档操作出现了一些问题, 有几个重复的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等, 这部分请看官方文档自行学习吧. 我要做的是企业内部项目. 所以这块先不研究了.

也有可能会使用Auth0, Stormpath这样的OAuth Provider, Auth0我用过, 登陆有点慢, 但功能很强大. 这个也不讲了, 他们的文档写的很好, 也给出了各种客户端的代码, 很容易集成.

Javascript 客户端

这将是最后一部分.

手头的项目有点急.  过几天再写这个.

使用Identity Server 4建立Authorization Server (5)的更多相关文章

  1. 从头编写asp.net core 2.0 web api 基础框架 (5) + 使用Identity Server 4建立Authorization Server (7) 可运行前后台源码

    前台使用angular 5, 后台是asp.net core 2.0 web api + identity server 4. 从头编写asp.net core 2.0 web api 基础框架: 第 ...

  2. 使用Identity Server 4建立Authorization Server

    使用Identity Server 4建立Authorization Server (6) - js(angular5) 客户端 摘要: 预备知识: http://www.cnblogs.com/cg ...

  3. 使用Identity Server 4建立Authorization Server (1)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 本文内容基本完全来自于Identity Server 4官方文档: https://identitys ...

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

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

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

    第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第一部分主要是建立了一个简单的Identity Server. 接下来继续: 建立Web Api项目 ...

  6. 使用Identity Server 4建立Authorization Server (3)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  7. 使用Identity Server 4建立Authorization Server (6) - js(angular5) 客户端

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  8. ASP.NET Core3.1使用Identity Server4建立Authorization Server

    前言 网上关于Identity Server4的资料有挺多的,之前是一直看杨旭老师的,最近项目中有使用到,在使用.NET Core3.1的时候有一些不同.所以在此记录一下. 预备知识: https:/ ...

  9. 三、IDS4建立authorization server

    建立authorization server 一.环境搭建 1.创建项目 2.引用NuGet的identityserver4 3.配置asp.net core 管道 打开Startup.cs, 编辑C ...

随机推荐

  1. Quartz学习——Quartz大致介绍(一)

    1. 介绍 Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,是完全由java开发的一个开源的任务日程管理系统,"任务进度管理器"就是 ...

  2. 分布式系统中生成全局ID的总结与思考

    世间万物,都有自己唯一的标识,比如人,每个人都有自己的指纹(白夜追凶给我科普的,同卵双胞胎DNA一样,但指纹不一样).又如中国人,每个中国人有自己的身份证.对于计算机,很多时候,也需要为每一份数据生成 ...

  3. Bayesian CTR Prediction for Bing

    Microsoft published a paper in ICML 2009 named ‘Web-Scale Bayesian Click-Through Rate Prediction for ...

  4. zoj3211dream city dp 斜率

    Dream City Time Limit: 1 Second      Memory Limit:32768 KB JAVAMAN is visiting Dream City and he see ...

  5. Feature Scaling深入理解

    Feature Scaling 可以翻译为特征归一化,或者数据归一化,比如统计学习中,我们一般都会对不同量纲的特征做归一化,深度学习中经常会谈到增加的BN层,LRN层会带来训练收敛速度的提升,等等.问 ...

  6. asp.net中使用Global.asax文件中添加应用出错代码,写入系统日志文件或数据库

    void Application_Error(object sender, EventArgs e) { // 在出现未处理的错误时运行的代码 Exception objErr = Server.Ge ...

  7. 热门开源项目:Guns-后台管理系统

    Guns基于SpringBoot,致力于做更简洁的后台管理系统,完美整合springmvc + shiro + mybatis-plus + beetl!Guns项目代码简洁,注释丰富,上手容易,同时 ...

  8. 改变oracle数据库归档模式_译文

    Changing the Database Archiving Mode 改变数据库归档模式. Purpose 目的 This module describes how you can change ...

  9. Java-JMS Bug记录

    1.Junit测试时,使用for循环发送JMS(ReportQuestionSender)的时候,监听器(ReportQuestionListener)只接受到一条消息. 原因:使用Junit测试会阻 ...

  10. Win10 UWP xaml 延迟加载元素

    xaml新增x:DeferLoadStrategy里面只有Lazy,查询了百度看到MSP_甄心cherish大神说的 xaml使用x:DeferLoadStrategy="Lazy" ...