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

预备知识: 学习Identity Server 4的预备知识

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

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

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

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

之前的配置都是在内存中, 下面将如何把这些数据存储到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 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()方法已经包含了这个中间件. 然后使用命令行执行:

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 客户端

这将是最后一部分.

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

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


.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/322969.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

idea如何安装lombok

https://github.com/mplushnikov/lombok-intellij-plugin/releases &#xff0c;Plugins -> Install plugin from disk… 选择下载的zip包安装&#xff0c;重启idea即可。 依赖包 <dependency><groupId>org.projectlombok</groupId><artifactId>lom…

好好说说Java中的常量池之Class常量池

转载自 好好说说Java中的常量池之Class常量池 在Java中&#xff0c;常量池的概念想必很多人都听说过。这也是面试中比较常考的题目之一。在Java有关的面试题中&#xff0c;一般习惯通过String的有关问题来考察面试者对于常量池的知识的理解&#xff0c;几道简单的String面试…

jzoj3085-图的计数【组合数,数论】

正题 题目大意 求有多少个m条边的有向图使得1到n的最短路长度为n-1 解题思路 首先长度为n−1n-1n−1那么就是1到n得先是一条链。在链上加m−n1m-n1m−n1条边且不能加如捷径边。 捷径边的条数为Cn−12C_{n-1}^2Cn−12​&#xff0c;然后可以加的边数就是n∗n−Cn−12n*n-C_{n-…

spring cloud+.net core搭建微服务架构:Api授权认证(六)

前言 这篇文章拖太久了&#xff0c;因为最近实在太忙了&#xff0c;加上这篇文章也非常长&#xff0c;所以花了不少时间&#xff0c;给大家说句抱歉。好&#xff0c;进入正题。目前的项目基本都是前后端分离了&#xff0c;前端分Web&#xff0c;Ios,Android。。。,后端也基本是…

如何用spring boot写一个注册页面

环境准备&#xff1a; java集成开发环境&#xff1a;IDEA 数据库&#xff1a;Mysql Maven 最好在安装有个navicat&#xff08;数据库可视化界面&#xff09; 安装好上述几个软件后 总结下&#xff1a;五步 1、创建新的工程 2、创建建applicatiom.yml 3、创建entity层 4、创建r…

Oracle入门(一)之入门级知识详解

转载自 Oracle入门级知识详解 一. Oracle基本介绍 1. 什么时候用Oracle数据库&#xff1f; SQL SERVER 号称百万级数据&#xff08;一个表的数据&#xff09;&#xff0c;但是其实做多20万条数据 超过20万条数据就用Oracle 2. Oracle的版本 Oracle8i/9i(internet)基于网络…

jzoj3086,luogu3831-[SHOI2012]回家的路【最短路,拆点】

正题 luogu评测记录:https://www.luogu.org/recordnew/lists?uid52918&pidP3831 题目大意 有n∗nn*nn∗n的铁路网走一格代价为2&#xff0c;mmm个中转站可以改变方向代价为1。求两个点之间的最短路。 解题思路 我们发现n∗nn*nn∗n很大&#xff0c;所以我们考虑根据mmm…

活动:北京Xamarin分享会第8期(2017年11月11日)

本期活动内容预告&#xff1a; 分享主题1: Tech Summit 2017大会课程 - 21世纪不动产使用Xamarin和Azure案例。 分享者&#xff1a;周岳, 微软MVP (Xamarin) , 北京视高盛景软件首席架构师 分享主题2: Tech Summit 2017大会课程 - AI: 清清爽爽几步&#xff0c;打造专属视觉分…

IDEA创建包不是树形

创建包的时候和别人的不一样&#xff0c;不是树形结构 可以点击图中的齿轮改变选项 把两个对勾取消掉就可以了 现在就是树形结构了

.NET Core跨平台的奥秘[下篇]:全新的布局

从本质上讲&#xff0c;按照CLI规范设计的.NET从其出生的那一刻就具有跨平台的基因&#xff0c;这与Java别无二致。由于采用了统一的中间语言&#xff0c;微软只需要针对不同的平台设计不同的虚拟机&#xff08;运行时&#xff09;就能弥合不同操作系统与处理器架构之间的差异&…

漫画:什么是拜占庭将军问题

转载自 漫画&#xff1a;什么是拜占庭将军问题 什么是拜占庭将军问题&#xff1f; 在很久很久以前&#xff0c;拜占庭是东罗马帝国的首都。那个时候罗马帝国国土辽阔&#xff0c;为了防御目的&#xff0c;因此每个军队都分隔很远&#xff0c;将军与将军之间只能靠信使传递消息…

欢乐纪中某A and B组赛【2019.1.23】

前言 翻车的更惨 成绩 RankRankRank是有算别人的 RankRankRankPersonPersonPersonScoreScoreScoreAAABBBCCC2929292017myself2017myself2017myself1601601607070700009090903636362017zyc2017zyc2017zyc1401401407070701010106060605454542017lw2017lw2017lw10010010050505000…

2019年度总结

还有两天就是2020年了&#xff0c;因此写一篇年度总结吧&#xff0c;以后争取每年都会写一篇的。 2019年回顾&#xff1a; 收获 2019年真是神奇的一年&#xff0c;对我而言&#xff0c;这一年收获的东西非常多&#xff0c;是我真正的入门编程的一年。 从二月份入门java到现在…

SQL Server 审计

审计&#xff08;Audit&#xff09;用于追踪和记录SQL Server实例或数据库中发生的事件&#xff0c;审计主要包括审计对象&#xff08;Audit&#xff09;和审计规范&#xff08;Audit Specification&#xff09;&#xff0c;创建审计首先需要创建一个SQL Server 实例级的审计对…

Hadoop入门(十九)Mapreduce的最大值程序

一、简介 最大值是统计中最常使用到的&#xff0c;现在使用Mapreduce在海量数据中统计数据的最大值。 二、例子 &#xff08;1&#xff09;实例描述 给出三个文件&#xff0c;每个文件中都存储了若干个数值&#xff0c;求所有数值中的最大值。 样例输入&#xff1a; …

jzoj3913-艰难的选择【差分,统计】

正题 题目大意 一个01串&#xff0c;求最长的子串使得0和1都相等。 解题思路 维护差分数组zzz&#xff0c;vixv_ixvi​x表示iii最早出现在差分数组的那个数字。枚举尾部&#xff0c;用viv_ivi​ codecodecode #include<cstdio> #include<algorithm> #include<…

ASP.NET Core中的OWASP Top 10 十大风险-失效的访问控制与Session管理

本博文翻译自&#xff1a; https://dotnetcoretutorials.com/2017/10/16/owasp-top-10-asp-net-core-broken-authentication-session-management/ 在我们之前关于OWASP Top 10的文章中&#xff0c;我们讨论了SQL注入。SQL注入有一个非常明确的解释和例子&#xff0c;但这次我们…

Hadoop入门(二十)Mapreduce的最小值程序

一、简介 最小值是统计中最常使用到的&#xff0c;现在使用Mapreduce在海量数据中统计数据的最小值。 二、例子 &#xff08;1&#xff09;实例描述 给出三个文件&#xff0c;每个文件中都存储了若干个数值&#xff0c;求所有数值中的最小值。 样例输入&#xff1a; …

jzoj3914-人品问题【树形dp】

正题 题目大意 一棵树每个点有权值&#xff0c;选择kkk个点&#xff0c;要求选子节点之前必须要选父节点。求最大权值。 解题思路 树形背包限制一下必须选kkk个就好了 codecodecode #include<cstdio> #include<algorithm> #include<cstring> #define N 11…

Docker部署运行微服务

1、环境准备&#xff1a; 主机&#xff1a; X-shell X-ftp jar包 这里只说下jar包&#xff0c;另外两个到官网下载即可 Idea打包jar包流程 先按这四步走 先点击左下的框框&#xff0c;再点击maven&#xff0c;出现右边的窗口&#xff0c;点击clean&#xff0c;再点击package&…