asp .net core 集成swagger+id4

资料:

使用客户端凭据保护 API — IdentityServer4 1.0.0 文档 (identityserver4docs.readthedocs.io)

  1. 集成swagger

    1. 引包 Swashbuckle.AspNetCore

      程序包命令
      Install-Package Swashbuckle.AspNetCore -Version 6.6.2
      
    2. 添加swagger中间件

      1. builder.Services.AddSwaggerGen();
    3. 使用swagger中间件

      1. //启用swagger
        app.UseSwagger();
        app.UseSwaggerUI();
    4. 输入https://localhost:<port>/swagger 即可打开swagger UI

      image

  2. 集成 IdentityServer4

    1. 引包

      IdentityServer4

    2. 创建配置文件

      1. Config.cs (IdentityServer 资源和客户端配置文件)

        public class Config
        {
            public static IEnumerable<ApiScope> ApiScopes =>
            new List<ApiScope>
            {
                new ApiScope("api1", "My API")
            };
        
            public static IEnumerable<Client> Clients =>
                new List<Client>
                {
                    new Client
                    {
                        ClientId = "client",
        
                        // 没有交互式用户,使用 clientid/secret 进行身份验证
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
        
                        // 用于身份验证的密钥
                        ClientSecrets =
                        {
                            new IdentityServer4.Models.Secret("secret".Sha256())
                        },
        
                        // 客户端有权访问的范围
                        AllowedScopes = { "api1" }
                    }
                };
        }
        
    3. 添加中间件

      builder.Services.AddIdentityServer()
              .AddDeveloperSigningCredential()        //这仅适用于没有证书可以使用的开发场景。
              .AddInMemoryApiScopes(Config.ApiScopes)
              .AddInMemoryClients(Config.Clients);
      
    4. 使用id中间件

      app.UseIdentityServer();
      
    5. 可能出现跨域的问题,使用cors 解决

      builder.Services.AddCors(c =>
      {
          c.AddPolicy("test", option =>
          {
              option.AllowAnyHeader();
              option.AllowAnyMethod();
              option.AllowAnyOrigin();
          });
      });
      
      
      app.UseCors("test");
      

      注:app.UseCors()需要在app.UseIdentityServer()之前注册,否则无法生效,IdentityServer4文档 说明如下:

      image

  3. 在web api使用Id4 进行授权

    1. 新增SecurityRequirementsOperationFilter类

      public class SecurityRequirementsOperationFilter : IOperationFilter
      {
          public void Apply(OpenApiOperation operation, OperationFilterContext context)
          {
              // Policy names map to scopes
              var requiredScopes = context.MethodInfo .GetCustomAttributes(true) //方法加小锁
                  .Union(context.MethodInfo.DeclaringType.GetCustomAttributes(true)) //controller 加小锁
                  .OfType<AuthorizeAttribute>()
                  .Select(attr => attr.Policy)
                  .Distinct();
      
              if (requiredScopes.Any())
              {
                  operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
                  operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
      
                  //添加UI上的锁按钮
                  var oAuthScheme = new OpenApiSecurityScheme
                  {
                      Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                  };
      
                  operation.Security = new List<OpenApiSecurityRequirement>
                  {
                      new OpenApiSecurityRequirement
                      {
                          [ oAuthScheme ] = requiredScopes.ToList()
                      }
                  };
              }
          }
      }
      
    2. Program.cs增加认证授权配置

      //注入id4
      builder.Services.AddAuthentication("Bearer")
                  .AddJwtBearer("Bearer", options =>
                  {
                      options.Authority = "http://localhost:5263";//id4服务地址
      
                      options.TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidateAudience = false
                      };
                      options.RequireHttpsMetadata = false;
                  });
      
      
      
      //添加swagger
      builder.Services.AddSwaggerGen(c => {
          c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
          {
              Type = SecuritySchemeType.OAuth2,
              Flows = new OpenApiOAuthFlows
              {
                  ClientCredentials = new OpenApiOAuthFlow
                  {
                      AuthorizationUrl = new Uri("http://localhost:5263/connect/authorize"),
                      TokenUrl = new Uri("http://localhost:5263/connect/token"),
                      //Scopes = new Dictionary<string, string>
                      //{
                      //    { "api1", "api1" }
                      //}
                  }
              }
          });
          //添加api授权的按钮,在Header中添加token,传递到后台
          c.OperationFilter<SecurityRequirementsOperationFilter>();
      });
      
posted @ 2025-07-14 15:33  排骨锅包肉  阅读(9)  评论(0)    收藏  举报