IdentityServer4实现.Net Core API接口权限认证(快速入门)
什么是IdentityServer4
官方解释:IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现。
通俗来讲,就是服务端对需要认证授权的资源(客户端请求资源)在外层使用IdentityServer4框架进行封装加壳,用户只能通过获取IdentityServer4颁发的Token令牌才能进行资源访问。
下面开始进入正题,如何快速搭建实现API接口鉴权。
准备:1.下载准备NetCore sdk环境
2.本文开发环境为VS2019,部分代码可能和之前的版本不同。
第一步,新建权限认证服务项目,本文以Net Core API项目模板为例(也可以选择其他模板)

第二步,添加IdentityServer4 Nuget程序包。不同版本依赖的NetCoe sdk环境不同,需手动选择合适版本。

这里提醒一下,有些同学的系统可能添加Nuget程序包时,发现无法找到程序包。我们这里找出了解决方法,点击Nuget程序包添加页面的右上角设置按钮,看到如下页面,手动添加如下的nuget.org,然后重新搜索即可。

第三步,添加IdentityServer4配置管理类。本文以用户密码授权模式为例。
1 public class Config
2 {
3 /// <summary>
4 /// 定义资源范围
5 /// </summary>
6 public static IEnumerable<ApiResource> GetApiResources()
7 {
8 return new List<ApiResource>
9 {
10 new ApiResource("api1", "我的第一个API")
11 };
12 }
13
14 /// <summary>
15 /// 定义访问的资源客户端
16 /// </summary>
17 /// <returns></returns>
18 public static IEnumerable<Client> GetClients()
19 {
20 return new List<Client>
21 {
22 new Client{
23 ClientId="client",//定义客户端ID
24 ClientSecrets=
25 {
26 new Secret("secret".Sha256())//定义客户端秘钥
27 },
28 AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,//授权方式为用户密码模式授权,类型可参考GrantTypes枚举
29 AllowedScopes={ "api1"}//允许客户端访问的范围
30
31 }
32 };
33 }
34
35 /// <summary>
36 /// 这个方法是来规范tooken生成的规则和方法的。一般不进行设置,直接采用默认的即可。
37 /// </summary>
38 /// <returns></returns>
39 public static IEnumerable<IdentityResource> GetIdentityResources()
40 {
41 return new IdentityResource[]
42 {
43 new IdentityResources.OpenId()
44 };
45 }
46 }
第四步,Startup启动类中注册服务中间件
1 // This method gets called by the runtime. Use this method to add services to the container.
2 public void ConfigureServices(IServiceCollection services)
3 {
4 services.AddIdentityServer()//注册服务
5 .AddDeveloperSigningCredential()
6 .AddInMemoryApiResources(Config.GetApiResources())//配置类定义的授权范围
7 .AddInMemoryClients(Config.GetClients())//配置类定义的授权客户端
8 .AddTestUsers(new List<TestUser> { new TestUser { Username = "Admin", Password = "123456", SubjectId = "001", IsActive = true } });//模拟测试用户,这里偷懒了,用户可以单独管理,最好不要直接在这里New
9 services.AddControllers();
10 }
11
12 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
13 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
14 {
15 if (env.IsDevelopment())
16 {
17 app.UseDeveloperExceptionPage();
18 }
19
20 app.UseIdentityServer();//添加中间件
21
22 app.UseHttpsRedirection();
23
24 app.UseRouting();
25
26 app.UseAuthorization();
27
28 app.UseEndpoints(endpoints =>
29 {
30 endpoints.MapControllers();
31 });
32 }
应用程序默认的端口号有两种:1.http://localhost:5000 2.https://localhost:5001.
到这里,Identityserver4鉴权服务已经简单搭建完成。我们直接在VS中启动项目。并在端口号后面加上/.well-known/openid-configuration,出现如下页面则表示配置成功。

第五步,PostMan模拟请求获取token(当然这一步非必须,对postman感兴趣的同学可以试一试)
我们都知道IdentityServer4需要客户端先访问鉴权服务获取token令牌,才能进一步访问加权的服务器资源。我们这里先通过PostMan模拟客户端请求,获取Token。(postman工具大家可以网上下载,也可以使用谷歌自带的postman插件)
1.使用postman请求token时,有个地方需要注意下:
很多同学在使用https请求时,即请求https://localhost:5001,会发现无法成功。因为postman默认把SSL证书认证打开了,我们可以手动关闭掉。找到postman页面右上方的小扳手图标,进入设置页面找到ssl关掉即可。当然同学们直接使用http://localhost:5000请求就无需设置SSL.

2.请求参数
这里的参数value就是我们在鉴权服务配置类设置的client和TestUser信息。
Grant_Type为授权类型,本文我们使用的是用户密码模式,所以这里填password.

这里我们看到,我们已成功模拟请求获取了Token。大功告成,鉴权服务已验证可用,我们赶紧去发布部署吧。
第六步,鉴权服务发布部署。
.Net Core发布模式有三种:
1.框架依赖+可移植
2.框架依赖+运行时环境(带可执行程序exe)
3.独立部署
简单来说,框架依赖模式发布的程序包,都需要部署环境自带.net core等运行环境;而独立部署则不需要考虑,发布包已经包含了运行环境,直接部署即可。
下面本文以框架依赖+可移植发布,做简单介绍。

发布完成后,我们会在发布路径中看到程序dll.我们找到发布路径,通过CMD命令窗口:dotnet xxx.dll可直接启动。

如上,则表示启动成功。(如果其他发布模式,直接双击发布包中可执行exe文件即可启动)
鉴权服务部署完成后,我们API接口如何使用呢,下面开始正式介绍。
第一步:新建Web Api项目

添加Nuget程序包

第二步:配置启动类
1 public void ConfigureServices(IServiceCollection services)
2 {
3 //注册服务
4 services.AddAuthentication("Bearer")
5 .AddIdentityServerAuthentication(x =>
6 {
7 x.Authority = "http://localhost:5000";//鉴权服务地址
8 x.RequireHttpsMetadata = false;
9 x.ApiName = "api1";//鉴权范围
10 });
11 services.AddControllers();
12 }
13
14 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
15 {
16 if (env.IsDevelopment())
17 {
18 app.UseDeveloperExceptionPage();
19 }
20 app.UseAuthentication();//添加鉴权认证
21 app.UseHttpsRedirection();
22 app.UseRouting();
app.UseAuthorization();
23 app.UseEndpoints(endpoints =>
24 {
25 endpoints.MapControllers();
26 });
27 }
应用程序默认的端口号有两种:1.http://localhost:5000 2.https://localhost:5001.为了避免端口号冲突被占用,我们可以在Program类中修改应用程序启动端口号。
1 public static IHostBuilder CreateHostBuilder(string[] args) =>
2 Host.CreateDefaultBuilder(args)
3
4 .ConfigureWebHostDefaults(webBuilder =>
5 {
6 webBuilder.UseUrls("http://*:5555");//设置启动端口号
7 webBuilder.UseStartup<Startup>();
8 });
第三步:创建API DEMO
1 [Route("api/[controller]")]
2 [ApiController]
3 public class TestController : ControllerBase
4 {
5 // GET: api/Test
6 /// <summary>
7 /// 方法加权
8 /// </summary>
9 /// <returns></returns>
10 [Authorize]
11 [HttpGet]
12 public IEnumerable<string> Get()
13 {
14 return new string[] { "value1", "value2" };
15 }
16
17 /// <summary>
18 /// 方法未加权 可直接访问
19 /// </summary>
20 /// <param name="id"></param>
21 /// <returns></returns>
22 // GET: api/Test/5
23 [HttpGet("{id}", Name = "Get")]
24 public string Get(int id)
25 {
26 return "value";
27 }
28
29 /// <summary>
30 /// 开放获取token API 接口
31 /// </summary>
32 /// <returns></returns>
33 [HttpGet("GetToken")]
34 public async Task<string> GetToken()
35 {
36 var client = new HttpClient();
37 var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
38 {
39 Address = "http://localhost:5000/connect/token",
40 ClientId = "client",
41 ClientSecret = "secret",
42 Scope = "api1",
43 UserName = "Admin",
44 Password = "123456",
45 });
46
47 if (tokenResponse.IsError)
48 {
49 return tokenResponse.Error;
50 }
51
52 return tokenResponse.AccessToken;
53
54 }
55 }
1.接口方法上加上:
[Authorize]
相当于对接口加权,只有被授权的用户才能访问(即获取token的用户)。此时上文中接口api/Test由于被加权,请求时会报错;但是api/Test/1接口未加权,仍可正常请求。
那么我们如何才能访问被加权的接口呢???Go Next
2.我们这里开放了获取Token的接口GetToken(类似于上文中通过PostMan获取Token)
访问被加权的API接口,我们这里需要先请求获取Token,然后请求加权接口时带上token参数。

3.请求加权接口

请求加权接口时带上Token,接口请求成功!
OK,关于如何快速开发和调试基于IdentityServer4框架的API接口鉴权服务,至此我们已介绍完毕。
小弟不才,本文中有考虑不周全或错误的地方,欢迎大家指正。
(如果有的同学想通过IIS部署API应用程序,这里有个地方需要注意下,需要在IIS(功能视图——模块)中添加AspNetCoreModule模块。具体原因本文就不在这里介绍了。)
