如何在 Scalar 中为 .NET 9 应用程序全局添加 JWT 令牌支持?

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

我正在努力在 .NET 9 应用程序中启用 Scalar,并且需要将其配置为全局使用 JWT 令牌,类似于 Swagger 允许全局添加 JWT 令牌身份验证的方式。但是,我找不到任何有关如何使用 Scalar 实现此目的的文档或示例。

是否可以在 Scalar 中设置全局 JWT 令牌支持?如果可以,如何实施?任何示例或指导将不胜感激!

//other codes
services.AddOpenApi();
//other codes
app.MapOpenApi();
app.MapScalarApiReference(options =>
{
    options.WithTheme(ScalarTheme.Moon)
        .WithDarkMode(true)
        .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
        .WithDarkModeToggle(false)
        .WithPreferredScheme("Bearer")
        .WithHttpBearerAuthentication(bearer =>
        {
            bearer.Token = "your-bearer-token";
        });
    options.Authentication = new ScalarAuthenticationOptions
    {
        PreferredSecurityScheme = "Bearer"
    };
});

套餐:

  • 标量.AspNetCore (1.2.49)
  • Microsoft.AspNetCore.OpenApi (9.0.0)
c# asp.net .net openapi scalar
1个回答
0
投票

感谢这篇文章:https://github.com/scalar/scalar/issues/4055

身份验证类型加载存在问题;)

替换这个->

builder.Services.AddOpenApi();

这样 ->

builder.Services.AddOpenApi("v1", options => { options.AddDocumentTransformer<BearerSecuritySchemeTransformer>(); });

internal sealed class BearerSecuritySchemeTransformer(Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
{
    public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
    {
        var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();
        if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer"))
        {
            var requirements = new Dictionary<string, OpenApiSecurityScheme>
            {
                ["Bearer"] = new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer", 
                    In = ParameterLocation.Header,
                    BearerFormat = "Json Web Token"
                }
            };
            document.Components ??= new OpenApiComponents();
            document.Components.SecuritySchemes = requirements;

            foreach (var operation in document.Paths.Values.SelectMany(path => path.Operations))
            {
                operation.Value.Security.Add(new OpenApiSecurityRequirement
                {
                    [new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }] = Array.Empty<string>()
                });
            }
        }
    }
}

然后你应该看到类似这样的东西 标量用户界面

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