Swagger UI 未在 ASP.NET Core REST API 中发送 OAuth2 的 client_id 和 client_secret

问题描述 投票:0回答:1

如果您正在使用简单的 REST API,并且遇到 Swagger UI 无法正确发送 OAuth2 客户端凭证流的 client_id 和 client_secret 的问题,并且您希望在 StackOverflow 上提问,您可能需要提供简洁而全面的概述的问题。您可以按照以下方式提出问题:

标题: Swagger UI 未在 ASP.NET Core REST API 中发送 OAuth2 的 client_id 和 client_secret

身体: 我正在 ASP.NET Core REST API 中实现 OAuth2 客户端凭据流,并使用 Swagger UI 来测试端点。虽然 Swagger UI 在“授权”弹出窗口中正确显示 client_id 和 client_secret 的输入字段,但对令牌端点的实际请求不包含这些字段。相反,它只发送 grant_type=client_credentials,导致我的服务器出现“400 Bad Request”错误,表明 client_id 和 client_secret 丢失。

这是我的 Startup.cs 中的相关 Swagger 配置:

`services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            ClientCredentials = new OpenApiOAuthFlow
            {
                TokenUrl = new Uri("/api/Auth/token", UriKind.Relative),
                // Optionally define scopes here if your implementation uses them
            }
        }
    });
    // Any other configurations
});`

我的令牌端点如下所示:

`[HttpPost("token")]
public IActionResult Token([FromForm] string client_id, [FromForm] string client_secret)
{
    // Token generation logic...
}`

使用 Swagger UI 进行测试时,我填写了

client_id 
client_secret
,但请求负载仅包含
grant_type=client_credentials
。 client_id 和 client_secret 丢失。

什么可能导致 Swagger UI 不发送 client_id 和 client_secret? 当我尝试在 Postman 中测试它并从 [Authorize] 端点获取请求时,它成功工作了。

我希望 Swagger UI 在使用 OAuth2 客户端凭据流程时能够正确地将 client_id 和 client_secret 发送到我的令牌端点,从而允许我直接从 UI 进行身份验证和测试安全端点。然而,尽管在 Swagger UI 中填写了这些字段,但仅发送

grant_type=client_credentials
,由于缺少
client_id 
client_secret.

,导致“400 错误请求”响应
c# rest oauth-2.0 swagger-ui restful-authentication
1个回答
0
投票

首先,这只是一个示例实现,只是为了介绍身份验证和授权的过程,我现在不打算在现实世界中使用它。 其次,除了使用 Oktta 或 Azure AD 等第三方应用程序之外,我还想根据 client_id 和 client_secret 生成 jwt 令牌...

从 swagger 上的授权按钮中,我填写了 id 和 client_secret 并将其发送到生成令牌的我的端点(在邮递员中)在 swagger 中,我收到错误: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.