【问题标题】:How to do OAuth2 Authorization in ASP.NET Core for Swagger UI using Swashbuckle如何使用 Swashbuckle 在 ASP.NET Core 中为 Swagger UI 进行 OAuth2 授权
【发布时间】:2019-08-21 06:46:17
【问题描述】:

DotNet Core 2 中带有客户端凭据流的 Swashbuckle OAuth2 授权

我想设置隐式FlowAuthorizationUrl,不同Scopes,默认选择Client-id, 所以,点击授权后,它应该导航到不同的选项卡,打开AuthorizationUrl 并使用户登录Swagger。所以,下次用户可以看到log out 选项。

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info()
    {
        Title = "",
        Description = "All rights reserved."
    });


    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
    {
        Flow = "implicit",
        AuthorizationUrl = "https://...",
        Scopes = new Dictionary<string, string> {
            { "", "Read/Write" }
        }

    });
});

Configure() 拥有,

app.UseSwagger();
app.UseSwaggerUI(c => {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "iModelAcquisitionService");
});

【问题讨论】:

    标签: asp.net-core swagger swashbuckle


    【解决方案1】:

    您可以尝试以下步骤来启用隐式 Oauth2 流:

    1. 更改 Startup.cs 并在 ConfigureServices 方法中替换之前添加的:

      services.AddSwaggerGen(c =>
      {
          c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
          c.AddSecurityDefinition("oauth2", new OAuth2Scheme
          {
              Type = "oauth2",
              Flow = "implicit",
              AuthorizationUrl = "https://login.microsoftonline.com/cb1c3f2e-a2dd-4fde-bf8f-f75ab18b21ac/oauth2/authorize",
              Scopes = new Dictionary<string, string>
              {
                      { "accessApi", "Access read operations" },
      
              },
              TokenUrl = "https://login.microsoftonline.com/cb1c3f2e-a2dd-4fde-bf8f-f75ab18b21ac/oauth2/token"
          });
      });
      
    2. 并在 Configure 方法中替换以下内容:

      app.UseSwagger();
      app.UseSwaggerUI(c =>
      {
          c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
          c.OAuthClientId("19c73866-562f-482a-bafb-89d9fe9b0aaa");
          c.OAuthAppName("Swagger Api Calls");
      
      
      });
      
    3. 进入swagger端点:http://localhost:xxx/swagger并点击Authorize按钮。

    【讨论】:

    • ClientId应该是什么,swagger不允许使用现有的appSettings.json的clientId,它们是不同的
    • client id 是您在身份提供者(Oauth 服务器)中注册的应用程序 id
    猜你喜欢
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多