Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT Authentication and Swagger with .NET Core 3.0

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 I expect. To do that, I added the code below:

services.AddSwaggerGen(c =>     {         c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My Web API", Version = "v1" });         c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme         {             Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",             Name = "Authorization",             In = ParameterLocation.Header,             Type = SecuritySchemeType.ApiKey         });     }); 

After adding AddSecurityDefinition function, I can see the Authorize button and when I click it, I see the form below: enter image description here

Then I type Bearer WhatEverApiKeyIsfgdgdgdg845734987fgdhgiher635kjh. After doing it, I expect to see authorization: Bearer WhatEverApiKeyIsfgdgdgdg845734987fgdhgiher635kjh in the request's header when I send a request to the Web API from Swagger, but authorization is not added to the request header. I am using SwashBuckle.Swagger(5.0.0-rc3). Please note there are many samples which work fine on .NET Core 2.0, but Swashbuckle swagger functions has changed on the latest version so I cannot use those samples.

like image 448
Nick Mehrdad Babaki Avatar asked Oct 01 '19 06:10

Nick Mehrdad Babaki


People also ask

How do I add authorization in swagger UI net core?

Create an ASP.NET Core Web API project in Visual Studio 2022 Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project.


1 Answers

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[] { }      }    }); }); 
like image 182
Nick Mehrdad Babaki Avatar answered Sep 20 '22 09:09

Nick Mehrdad Babaki