且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 JWT Bearer 令牌进行身份验证 Swagger

更新时间:2021-10-25 06:49:35

更新 - Swagger 规范已更改.检查下面@nilay 的答案以获得正确的解决方案.

我也遇到了同样的问题.

I had the very same problem.

两件事是必要的

  1. 您必须像这样放置 bearer <token-here>".只放令牌是行不通的.

  1. You have to put "bearer <token-here>" like this. Putting only token will not work.

要让它在 swagger 2.x 中工作,您需要在您的方案定义中附上相应的要求,以表明该方案适用于您 API 中的所有操作:

to get this to work in swagger 2.x, you need to accompany your scheme definition with a corresponding requirement to indicate that the scheme is applicable to all operations in your API:

c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
    { "Bearer", new string[] { } }
});

完整定义:

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Some API", Version = "v1" });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: "Authorization: Bearer {token}"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", new string[] { } }
                });
            });