使用IdentityServer4搭建鉴权服务

发布时间 2023-11-04 21:06:15作者: 江渔湖

  IdentityServer4是ASP.NET Core量身定制的JWT(son Web Token, token一种的格式 )服务框架,实现了OpenID Connect和 OAuth2.0协议(规范 认证授权中间件) 。

一、创建鉴权服务API

1.新建Core WebAPI进程服务:使用aminimal api,

     

    //顶级语句---脚本式编程

    var builder = WebApplication.CreateBuilder(args);

2.nuget IdentityServer4安装类库

   

 3.注册中间件-初始化数据

  首先注入

1 #region IOC
2 builder.Services.AddIdentityServer()//ids4怎么用的
3 .AddDeveloperSigningCredential()//临时生成的证书--即时生成的
4 .AddInMemoryClients(ClientInitConfig.GetClients())//InMemory 内存模式
5 .AddInMemoryApiScopes(ClientInitConfig.GetApiScopes())//指定作用域
6 .AddInMemoryApiResources(ClientInitConfig.GetApiResources());//能访问啥资源
7 #endregion

  调用

#region 中间件
app.UseIdentityServer();//使用这个中间件来处理请求
#endregion
  
ClientInitConfig类
 1 public class ClientInitConfig
 2 {
 3     public static IEnumerable<IdentityResource> IdentityResources =>
 4     new IdentityResource[]
 5     {
 6             new IdentityResources.OpenId(),
 7             new IdentityResources.Profile(),
 8     };
 9 
10     /// <summary>
11     /// 定义ApiResource   
12     /// 这里的资源(Resources)指的就是管理的API
13     /// </summary>
14     /// <returns>多个ApiResource</returns>
15     public static IEnumerable<ApiResource> GetApiResources()
16     {
17         return new[]
18         {
19                 new ApiResource("UserApi", "用户获取API")
20                 {
21                     Scopes={ "scope1" }//4.x必须写的
22                 }
23             };
24     }
25 
26     /// <summary>
27     /// Api范围---4.x新增的
28     /// </summary>
29     public static IEnumerable<ApiScope> GetApiScopes()
30     {
31         return new ApiScope[]
32           {
33                 new ApiScope("scope1"),
34                 new ApiScope("scope2"),
35           };
36     }
37 
38     /// <summary>
39     /// 定义验证条件的Client
40     /// </summary>
41     /// <returns></returns>
42     public static IEnumerable<Client> GetClients()
43     {
44         return new[]
45         {
46                 new Client
47                 {
48                     ClientId = "AspNetCore6.AuthDemo",//客户端唯一标识
49                     ClientName="Single AuthenticationCenter",
50                     ClientSecrets = new [] { new Secret("123456".Sha256()) },//客户端密码,进行了加密
51                     AllowedGrantTypes = GrantTypes.ClientCredentials,
52                     //授权方式,客户端认证,只要ClientId+ClientSecrets
53                     AllowedScopes = new [] { "scope1" },//允许访问的资源
54                     
55                     
56                     Claims=new List<ClientClaim>(){
57                         new ClientClaim(IdentityModel.JwtClaimTypes.Role,"Admin"),
58                         new ClientClaim(IdentityModel.JwtClaimTypes.NickName,"Admin"),
59                         //new ClientClaim(ClaimTypes.Role,"Admin"),
60                         //new ClientClaim(ClaimTypes.Name,"Admin"),
61                     }
62                 }
63             };
64     }
65 }

二、客户端集成Ids4

1.nuget IdentityServer4.AccessTokenValidation

2.增加鉴权+授权+特性

1 builder.Services.AddAuthentication("Bearer")//scheme--表示通过Bearer方式来解析用户信息
2      .AddIdentityServerAuthentication(options =>
3      {
4          options.Authority = "http://localhost:7200";//ids4的地址--专门获取公钥
5          options.ApiName = "UserApi";
6          options.RequireHttpsMetadata = false;
7      });//配置ids4
8 
9 var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

在接口方法前增加特性标记

  [Authorize]  //需要授权

三、网关集成Ids4

1.nuget IdentityServer4.AccessTokenValidation

2.配置鉴权服务

 1 #region Ids4
 2 var authenticationProviderKey = "UserGatewayKey";
 3 builder.Services.AddAuthentication("Bearer")
 4    .AddIdentityServerAuthentication(authenticationProviderKey, options =>
 5    {
 6        options.Authority = "http://localhost:7200";
 7        options.ApiName = "UserApi";
 8        options.RequireHttpsMetadata = false;
 9        options.SupportedTokens = SupportedTokens.Both;
10    });
11 #endregion

3.配置文件匹配

  配置文件中添加配置

    "AuthenticationOptions": {
        "AuthenticationProviderKey": "UserGatewayKey",
        "AllowedScopes": []
      },