编程语言
首页 > 编程语言> > asp.net core swagger传bearer token

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按钮

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

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

标签:core,requirement,asp,bearer,new,scheme,options,Authorization
来源: https://www.cnblogs.com/mryux/p/15920496.html