proudmonkey/ApiBoilerPlate

Swagger authorization not working (401 error)

Closed this issue · 3 comments

First, THANK YOU for creating and sharing the template.

Background: The ApiBoilerPlate was used to generate a WebAPI project. After adding [Authorize] attribute to the PersonsController, the endpoints require to Bearer JWT access token as expected. However, accessing any endpoint in the PersonsController will get 401.

Issue - Para authorization and bearer token are not included in the header upon submit in Swagger. External testing using Postman worked fine.

Fix - Made the following changes in Infrastructure\Installers\RegisterSwagger.cs

            options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Scheme = "Bearer",
                Description = "Enter 'Bearer' following by space and JWT.",
                Name = "Authorization",
                //Type = SecuritySchemeType.Http,
                Type = SecuritySchemeType.ApiKey,
                In = ParameterLocation.Header,
            });

See below for the code -
https://github.com/workcontrolgit/EmployeeProfileWebAPIDemo/blob/master/EmployeeProfile/EmployeeProfile/Infrastructure/Installers/RegisterSwagger.cs

I will fork and submit a pull request.

@workcontrolgit

Thanks for the feedback! Bearer tokens should use http SecuritySchemeType. The ApiKey type is used for Api Keys and cookie authentication. Read more here: https://swagger.io/docs/specification/authentication/

Which version of Swashbuckle.AspNetCore.Swagger you are using? If you are using version 5.5.x then you can do something like this:

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "MyApi", Version = "v1" });

    var securityScheme = new OpenApiSecurityScheme
    {
        Name = "JWT Authentication",
        Description = "Enter JWT token.",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "bearer",
        BearerFormat = "JWT",
        Reference = new OpenApiReference
        {
            Id = JwtBearerDefaults.AuthenticationScheme,
            Type = ReferenceType.SecurityScheme
        }
    };

    options.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        { securityScheme, new string[] { } }
    });
});

This is also nice since you don't need to have the "bearer JWTtoken" anymore in Swagger but just "JWTtoken".

Just don't forget to add:

options.OperationFilter<SwaggerAuthorizeCheckOperationFilter>();

to the end of AddSwaggerGen() :)

There is a nice article on this at https://codeburst.io/api-security-in-swagger-f2afff82fb8e

@proudmonkey
I use Swashbucket.AspNetCore.Swagger v5.1.0

@improwise
Thank you for the reference