JWT Authentication and Swagger with .Net core 3.0

后端 未结 6 827
我在风中等你
我在风中等你 2020-12-25 12:31

I am developing some Web Api with .Net core 3.0 and want to integrate it with SwashBuckle.Swagger. It is working fine, but when I add JWT authentication, it does not work as

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-25 12:53

    After some research, I eventually found the answer here

    Before seeing this page, I knew that I should use AddSecurityRequirement after AddSecurityDefinition because of many samples, but it was a problem that the function parameters have changed on .NET Core 3.0.

    By the way, the final answer is as below:

    services.AddSwaggerGen(c =>
    {
      c.SwaggerDoc("v1", new OpenApiInfo { 
        Title = "My API", 
        Version = "v1" 
      });
      c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
        In = ParameterLocation.Header, 
        Description = "Please insert JWT with Bearer into field",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey 
      });
      c.AddSecurityRequirement(new OpenApiSecurityRequirement {
       { 
         new OpenApiSecurityScheme 
         { 
           Reference = new OpenApiReference 
           { 
             Type = ReferenceType.SecurityScheme,
             Id = "Bearer" 
           } 
          },
          new string[] { } 
        } 
      });
    });
    

提交回复
热议问题