繁体   English   中英

Asp.net core Web API for SPA - How to implement Swagger Authentication without having to obtain the Access token outside of the Web API and pass it?

[英]Asp.net core Web API for SPA - How to implement Swagger Authentication without having to obtain the Access token outside of the Web API and pass it?

我们正在使用 React 和 ASP.Net 核心 Web API 构建一个 SPA。

React 会将 Auth_Token 传递给 ASP.Net 核心 Web API 进行身份验证,这是可行的。

As App Registration is done for the front-end application along with Scope & Roles , I am not sure how to implement Authentication for Swagger in ASP.Net core Web API.

目前我有以下swagger配置

    private void AddSwagger(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "Track Management API",
            });

            var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);

            c.IncludeXmlComments(xmlCommentsFullPath);

            var jwtSecurityScheme = new OpenApiSecurityScheme
            {
                Scheme = "bearer",
                BearerFormat = "JWT",
                Name = "JWT Authentication",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.Http,
                Description = "Put **_ONLY_** your JWT Bearer token on textbox below!",

                Reference = new OpenApiReference
                {
                    Id = JwtBearerDefaults.AuthenticationScheme,
                    Type = ReferenceType.SecurityScheme
                }
            };

            c.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);

            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                { jwtSecurityScheme, Array.Empty<string>() }
            });
        });
    }

目前,我们必须在 ASP.Net 核心 Web API 之外获取 Auth_Token 并将其传递给它。

在此处输入图像描述

开发者可以直接从 Swagger 页面生成所需的 Auth_Token 来简化这个过程吗?

Update: The below Swagger configuration try to get the required auth_code however it uses the Web API URL as the redirection URL and fails. What I want is that it should use the Front-end URL as the redirection URL to generate the auth_code but pass it to the Web API?

            c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Description = "OAuth2.0 Auth Code with PKCE",
                Name = "oauth2",
                Type = SecuritySchemeType.OAuth2,
                Flows = new OpenApiOAuthFlows
                {
                    AuthorizationCode = new OpenApiOAuthFlow
                    {
                        AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{this.Configuration.GetValue<string>("AzureAd:TenantId")}/oauth2/authorize"),
                        TokenUrl = new Uri($"https://login.microsoftonline.com/{this.Configuration.GetValue<string>("AzureAd:TenantId")}/v2.0/token"),
                        Scopes = new Dictionary<string, string>
                        {
                            { this.Configuration.GetValue<string>("AzureAd:ApiScope"), "Allows Read and Write" }
                        }
                    }
                }
            });
            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                    },
                    new[] { this.Configuration.GetValue<string>("AzureAd:ApiScope") }
                }
            }); 

The Other option that I see is to add the Web API URL as the redirect URL in the app registration for the lower environment.

您需要配置身份提供程序并将新的允许重定向 Uri 添加到/swagger/oauth2-redirect.html示例:

"RedirectUris": [
   "https://localhost:3379/authentication/login-callback", // for blazor client
   "https://localhost:3379/swagger/oauth2-redirect.html"   // for swagger client
]

这对我来说与 Azure AD B2C 结合使用:

config.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
    Type = SecuritySchemeType.OAuth2,
    Scheme = "oauth2",
    OpenIdConnectUrl = new Uri(builder.Configuration["AzureAd:Authority"]),
    Flows = new OpenApiOAuthFlows
    {
        Implicit = new OpenApiOAuthFlow
        {
            AuthorizationUrl = new Uri(builder.Configuration["AzureAd:Authority"], UriKind.Absolute),
            Scopes = new Dictionary<string, string>
                {
                    { builder.Configuration["AzureAd:Scopes"], "Access web API" },
                }
        }
    }
});

config.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
            },
            new[] { builder.Configuration["AzureAd:Scopes"] }
        }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM