Home > Software engineering >  .NET swagger authorization (jwt) without Bearer prefix
.NET swagger authorization (jwt) without Bearer prefix

Time:10-10

I have my own authorization middleware that reads jwt and get token from authorization header. Using swagger authorization :

builder.Services.AddSwaggerGen(option =>
{
    option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "Please enter a valid token",
        Name = "Authorization",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    option.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type=ReferenceType.SecurityScheme,
                    Id="Bearer"
                }
            },
            new string[]{}
        }
    });
});

i have always header like this: "Authorization: Bearer ".

I wonder if there is possibility to disable this 'Bearer' prefix and sending headers in: Authorization: form?

CodePudding user response:

Use SecuritySchemeType.ApiKey instead of .Http:

    option.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "Please enter a valid token",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });

This defines the Authorization: VALUE header without any value prefixes.

Remember to also add security requirements:

option.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" }
            },
            new string[] { }
        }
    });
  • Related