asp.net core swagger传bearer token

在program.cs中注入swagger的Authorize支持

builder.Services.AddSwaggerGen(options =>
{
    OpenApiSecurityScheme scheme = new OpenApiSecurityScheme()
    {
        Description = "Authorization header, ex:'Bearer 123456abcdef'",
        Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Authorization" },
        Scheme = "oauth2",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
    };

    options.AddSecurityDefinition("Authorization", scheme);
    OpenApiSecurityRequirement requirement = new OpenApiSecurityRequirement();
    requirement[scheme] = new List<string>();

    options.AddSecurityRequirement(requirement);
});

右上会出现Authorize按钮
asp.net core swagger传bearer token

由于没有输入jwt,调用hello出401错误

asp.net core swagger传bearer token

点击输入bearer %token%,之后再调用hello,可以看到header里包含了Authorization bearer信息,就没有问题了。

asp.net core swagger传bearer token

上一篇:wget常用命令汇总


下一篇:ASP.NET Core 6.0 使用 ServiceCollection