ASP.NET Core微服务之基于IdentityServer建立授权与验证服务(1)

释放双眼,带上耳机,听听看~!

Tip: 此篇已加入.NET Core微服务基础系列文章索引

一、IdentityServer的预备知识

要学习IdentityServer,事先得了解一下基于Token的验证体系,这是一个庞大的主题,涉及到Token,OAuth&OpenID,JWT,协议规范等等等等,园子里已经有很多介绍的文章了,个人觉得solenovex的这一篇文章《学习IdentityServer4的预备知识》言简意赅,可以快速的看看。另外savaboard的《ASP.NET Core 之 Identity 入门(一)》和《ASP.NET Core 之 Identity 入门(二)》这两篇也可以一看,对Claims和Identity的基本知识讲的比较通俗易懂,深入浅出,有故事情节,哈哈。

重点关注一下上面这张图(也是来自solenovex的文章),对于一个User(已注册)来说,他会首先向Authorization Server表明自己的身份(比如输入用户名和密码),然后Authorization Server为其发放了一个token,而这个token就好比是把家里的钥匙配了一把(clone)新的,此后该User就可以访问API请求获取Orders(订单)数据了。当然,实际中可能Authorization Server和API Server不在同一个区域内,它们可能只能遥望对方。此外,User还可以基于这个token去访问第三方服务,第三方服务会使用这个API来访问API Server,向其提供token比提供username&password要安全得多。

二、IdentityServer极简介绍

IdentityServer4(这里只使用版本号为4)是一个基于OpenID Connect和OAuth 2.0的针对ASP.NET Core 2.0的框架。IdentityServer是将规范兼容的OpenID Connect和OAuth 2.0终结点添加到任意ASP.NET Core应用程序的中间件。通常,你构建(或重新使用)包含登录和注销页面的应用程序,IdentityServer中间件会向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与其对话。

我们可以用IdentityServer来做啥?

(1)身份验证服务=>官方认证的OpenID Connect实现

(2)单点登录/注销(SSO)

(3)访问受控的API=>为不同的客户提供访问API的令牌,比如:MVC网站、SPA、Mobile App等

(4)等等等……

三、Started:第一个AuthorizationServer

1.1 建立一个ASP.NET Core空Web项目

建立ASP.NET Core项目,使用Empty空模板。

为了更好地查看日志信息,同时考虑到IISExpress启动起来真的很慢,修改lanuchSettings.json文件如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
1{
2  "profiles": {
3    "Manulife.DNC.MSAD.IdentityServer4Test": {
4      "commandName": "Project",
5      "launchBrowser": false,
6      "environmentVariables": {
7        "ASPNETCORE_ENVIRONMENT": "Development"
8      },
9      "applicationUrl": "http://localhost:5000/"
10    }
11  }
12}
13

1.2 安装并配置IdentityServer4

Step1.首先安装IdentityServer4:

NuGet>Install-Package IdentityServer4  

Step2.配置ASP.NET Core管道,即修改Configure方法


1
2
3
4
5
6
7
8
9
10
1    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
2    {
3        if (env.IsDevelopment())
4        {
5            app.UseDeveloperExceptionPage();
6        }
7
8        app.UseIdentityServer();
9    }
10

Step3.为了要把IdentityServer注册到容器中,需要对其进行配置,而这个配置中要包含三个信息:

(1)哪些API可以使用这个AuthorizationServer

(2)哪些Client可以使用这个AuthorizationServer

(3)哪些User可以被这个AuthrizationServer识别并授权

这里为了快速演示,我们写一个基于内存的静态类来快速填充上面这些信息(实际中,可以持久化在数据库中通过EF等ORM获取,也可以通过Redis获取):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
1    public class InMemoryConfiguration
2    {
3        public static IConfiguration Configuration { get; set; }
4        /// <summary>
5        /// Define which APIs will use this IdentityServer
6        /// </summary>
7        /// <returns></returns>
8        public static IEnumerable<ApiResource> GetApiResources()
9        {
10            return new[]
11            {
12                new ApiResource("clientservice", "CAS Client Service"),
13                new ApiResource("productservice", "CAS Product Service"),
14                new ApiResource("agentservice", "CAS Agent Service")
15            };
16        }
17
18        /// <summary>
19        /// Define which Apps will use thie IdentityServer
20        /// </summary>
21        /// <returns></returns>
22        public static IEnumerable<Client> GetClients()
23        {
24            return new[]
25            {
26                new Client
27                {
28                    ClientId = "client.api.service",
29                    ClientSecrets = new [] { new Secret("clientsecret".Sha256()) },
30                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
31                    AllowedScopes = new [] { "clientservice" }
32                },
33                new Client
34                {
35                    ClientId = "product.api.service",
36                    ClientSecrets = new [] { new Secret("productsecret".Sha256()) },
37                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
38                    AllowedScopes = new [] { "clientservice", "productservice" }
39                },
40                new Client
41                {
42                    ClientId = "agent.api.service",
43                    ClientSecrets = new [] { new Secret("agentsecret".Sha256()) },
44                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
45                    AllowedScopes = new [] { "agentservice", "clientservice", "productservice" }
46                }
47            };
48        }
49
50        /// <summary>
51        /// Define which uses will use this IdentityServer
52        /// </summary>
53        /// <returns></returns>
54        public static IEnumerable<TestUser> GetUsers()
55        {
56            return new[]
57            {
58                new TestUser
59                {
60                    SubjectId = "10001",
61                    Username = "edison@hotmail.com",
62                    Password = "edisonpassword"
63                },
64                new TestUser
65                {
66                    SubjectId = "10002",
67                    Username = "andy@hotmail.com",
68                    Password = "andypassword"
69                },
70                new TestUser
71                {
72                    SubjectId = "10003",
73                    Username = "leo@hotmail.com",
74                    Password = "leopassword"
75                }
76            };
77        }
78    }
79

   Step4.对于Token签名需要一对公钥和私钥,不过IdentityServer为开发者提供了一个_AddDeveloperSigningCredential()方法,它会帮我们搞定这个事,并默认存到硬盘中。当切换到生产环境时,还是得使用正儿八经的证书,更换为使用AddSigningCredential()_方法。


1
2
3
4
5
6
7
8
9
10
11
1    public void ConfigureServices(IServiceCollection services)
2    {
3        InMemoryConfiguration.Configuration = this.Configuration;
4
5        services.AddIdentityServer()
6            .AddDeveloperSigningCredential()
7            .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
8            .AddInMemoryClients(InMemoryConfiguration.GetClients())
9            .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());
10    }
11

1.3 获取你心心念念的Token

Step1.启动刚刚我们建立的AuthorizationServer程序,这里我们绑定的是5000端口。

Step2.启动Postman/SoapUI等API测试工具,通过向HTTP Body中填写数据发起POST请求:

Step3.发送一个错误的数据,看看返回的是啥?(这里输入了一个不在定义列表中的client_id)

Step4.查看控制台的日志信息:表示获取Token的这个请求成功了,日志中client_secret和password都是不会直接明文显示的。

Step5.IdentityServer中我们设置这几个API Service的Grant_Type是ResourceOwnerPasswordAndClientCredentials(点击这里了解=>资源拥有者密码凭据许可),因此我们还可以使用ClientCredentials(点击这里了解=>客户端凭据许可),如下所示:

Step6.再次查看控制台日志信息:这次没有关于User相关的任何信息显示了。

Step7.基本的开发结束,对于开发阶段,我们使用IdentityServer为开发者提供的临时证书即可,但是后面仍然需要生成一些正儿八经的证书。这里我们通过OpenSSL来生成,首先去官网下载一个,这里使用的是Win64_1.1版本。打开Powershell或者CMD,输入以下命令:

cmd>openssl req -newkey rsa:2048 -nodes -keyout cas.clientservice.key -x509 -days 365 -out cas.clientservice.cer
下面将生成的证书和Key封装成一个文件,以便IdentityServer可以使用它们去正确地签名tokens
cmd>openssl pkcs12 -export -in cas.clientservice.cer -inkey cas.clientservice.key -out cas.clientservice.pfx

中途会提示让你输入Export Password,这个password后面会用到,记住它。最终导出后的结果如下图所示:

这里我将其放到了项目结构文件夹中,并设置这个pfx文件为“如果较新则复制”,确保可以在最后生成的目录里边。现在就可以修改一下ConfigureServices()方法了:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1    public void ConfigureServices(IServiceCollection services)
2    {
3        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
4        InMemoryConfiguration.Configuration = this.Configuration;
5
6        services.AddIdentityServer()
7            //.AddDeveloperSigningCredential()
8            .AddSigningCredential(new X509Certificate2(Path.Combine(basePath,
9                Configuration["Certificates:CerPath"]),
10                Configuration["Certificates:Password"]))
11          .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
12          .AddInMemoryClients(InMemoryConfiguration.GetClients())
13        .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());
14    }
15

这里我将证书的路径和导出密码都写到了配置文件中:


1
2
3
4
5
6
7
1{
2  "Certificates": {
3    "CerPath": "certificate\\cas.clientservice.pfx",
4    "Password": "manulife"
5  }
6}
7

好,配置正儿八经的证书这一步骤Over。

四、IdentityServer QuickStart-UI

4.1 关于QuickStart UI

IdentityServer为我们提供了一套UI以便使我们能够快速地开发具有基本功能的认证/授权界面,我们可以去这个地址:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI/tree/release 下载,并将其复制到我们的项目目录中。

复制完成后,我们的项目结构如下图所示:

4.2 修改DI方法

(1)使用MVC与静态文件(由于wwwroot下有很多静态资源文件)


1
2
3
4
5
6
7
8
9
10
11
12
13
1    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
2    {
3        if (env.IsDevelopment())
4        {
5            app.UseDeveloperExceptionPage();
6        }
7
8        app.UseIdentityServer();
9        // for QuickStart-UI
10        app.UseStaticFiles();
11        app.UseMvcWithDefaultRoute();
12    }
13

(2)注册MVC


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1    public void ConfigureServices(IServiceCollection services)
2    {
3        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
4        InMemoryConfiguration.Configuration = this.Configuration;
5
6        services.AddIdentityServer()
7            //.AddDeveloperSigningCredential()
8            .AddSigningCredential(new X509Certificate2(Path.Combine(basePath,
9                Configuration["Certificates:CerPath"]),
10                Configuration["Certificates:Password"]))
11          .AddTestUsers(InMemoryConfiguration.GetUsers().ToList())
12          .AddInMemoryClients(InMemoryConfiguration.GetClients())
13          .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources());
14        // for QuickStart-UI
15        services.AddMvc();
16    }
17

4.3 Run  

(1)首页(这里由于我已经登录,所以这里会把我的账号显示了出来)

(2)Logout页,刚刚说到我已经实现Login了,所以我这里Logout一下

(3)Login页:这里只能识别我们在之前配置的静态User列表中那些User

登录之后,显示:"You have not given access to any applications",表示我们还没有给他授予访问任何API或网站模块的权限。后续我们会创建API和MVC网站来演示如何对其进行授权和访问。

五、小结

本篇主要简单的介绍了IdentityServer以及如何基于IdentityServer建立一个基本的AuthorizationServer,如何获取Token,以及集成QuickStart UI实现基本的界面展示。后续还会创建API和MVC网站,来和IdentityServer进行集成,以演示如何对User授予访问API和MVC网站的访问权限。

示例代码

Click => https://github.com/EdisonChou/EDC.IdentityServer4.Demo

参考资料

《identityserver4官方文档》=> 重点关注那些流程图与术语

ddrsql,《IdentityServer4之Resource Owner Password Credentials(资源拥有者密码凭据许可)》

ddrsql,《IdentityServer4之Client Credentials(客户端凭据许可)》

solenovex,《学习Identity Server4的预备知识》

solenovex,《使用Identity Server 4建立Authorization Server (1)》

solenovex,《使用Identity Server 4建立Authorization Server (2)》

solenovex,《使用Identity Server 4建立Authorization Server (3)》

给TA打赏
共{{data.count}}人
人已打赏
安全网络

CDN安全市场到2022年价值76.3亿美元

2018-2-1 18:02:50

安全经验

搜狗浏览器被曝重大安全漏洞 大量用户隐私被泄露

2013-11-5 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索