I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. Swagger UI runs as expected, the only issue is whenever I click on the Authorize green button on the swagger UI it will pop up but say Unknown Security definition type and give me two options Authorize and Close. It does not show under Available authorizations Bearer(http,Bearer) and allow me to enter a jwt value. I ran into this article that goes over bearer authentication but it isn't much help for me. Am I missing something in the .AddSwaggerGen()?
builder.Services.AddAuthorization();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Name = "Authorization",
Description = "Bearer Authentication with JWT Token",
Type = SecuritySchemeType.Http
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
});
var app = builder.Build();
app.UseAuthorization();
app.UseAuthentication();
......
I think Scheme should be "bearer" (lowercase b)
Scheme = "bearer",
You have used add authorization before defining your security definition.
First define security definition & then use add authorization
Related
I have some problem with JWT token. I have 2 apllication. 1st - Blazor webAssemble which has authentification in server side. And 2nd - web api. In second app i want use token from 1st app. In same server it's working. I can get token from wep api Blazor and use this token for [Authorize] method in 2nd web api. But if i deploy 2nd app in other server, i will have http code 401. All token will invalid in this scenario.
In asp net 4.5 identity used machineKey for decrypt token. And machineKey must be synchronize between servers for use one token. But i can't find how it's wotk in .net 6.
Anyone know something about this? Perhaps, some post about it.
This is programm.cs from 2nd app. App without outhorization.
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
// Add services to the container.
builder.Services.AddControllers();
TokenSettings tokenSettings = new TokenSettings();
configuration.Bind("Settings", tokenSettings);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSettings.Key)),
ValidIssuer = tokenSettings.Issuer,
ValidAudience = tokenSettings.Audience,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true
};
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(opt =>
{
opt.SwaggerDoc("v1", new OpenApiInfo { Title = "MyAPI", Version = "v1" });
opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
opt.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Thanks.
UPDATE
It was app.UseHttpsRedirection(); After publish i was using http and api did redirect. But i was receiving 401 from this code. Idk why. MessageBox.Show(response.StatusCode.ToString());
I have created an asp.net core project now, and I am making a swagger verification token, all of which are fine, but how to verify without adding the beginning of Bearer, what should I do?
enter image description here
If you want to omit the "Bearer" prefix tag, you can do this:
services.AddSwaggerGen(config =>
{
////Name the security scheme
config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization",
Name = "Authorization",
In = ParameterLocation.Header,
// Type = SecuritySchemeType.ApiKey,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat="JWT"
});
config.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
//The name of the previously defined security scheme.
Id = "Bearer"
}
},
new List<string>()
}
});
Note : If using SecuritySchemeType.ApiKey – token part should be
appended with ‘bearer’.
Note – If using SecuritySchemeType.Http – token need to be used
without “bearer”
Result:
This question already has answers here:
ASP Net Core 2.2 add locker icon only to methods that require authorization - Swagger UI
(3 answers)
Closed 2 years ago.
I have an ASP.Net Core Rest Web API documented with Swashbuckles's Swagger generation (.net v5 and Swashbuckle.AspNetCore v5.6.3). It generates Swagger documentation and UI with OAS3 support.
Also my API uses JWT bearer tokens. So, I added this code to the swagger configuration:
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Description = "Put `bearer` keyword in front of token"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme()
{
Reference = new OpenApiReference()
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
Array.Empty<string>()
}
});
And as expected, it added the authorization capability to the Swagger UI:
But I also noticed a few padlocks next to every HTTP request.
They are unlocked before authorization:
And after authorization they lock:
How could I get these padlocks to signal if authorization is required or not (I think I've seen the same padlocks somewhere doing this and it seems pretty natural to them to do this kind of thing as well)?
Already tried something like that, but it did not work (request headers no longer contained the jwt token):
options.OperationFilter<SecurityRequirementsOperationFilter>();
I figured out that the problem is that my Swagger is using OAS3 and SecurityRequirementsOperationFilter depending on OAS2. I've tried looking for alternatives, but it looks like there are no similar tools for OAS3.
What should I do?
Should I forget this feature? But that looks like the only purpose of these locks.
Are there any ways to have this feature and stay with OAS3 (also I not sure if I really need OAS3 support that much).
After some research, I found the answer here: https://stackoverflow.com/a/61365691/13851956.
So the code is:
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "No need to put the `bearer` keyword in front of token",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT"
});
options.OperationFilter<AuthorizationOperationFilter>();
public class AuthorizationOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata;
var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute);
var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute);
if (!isAuthorized || allowAnonymous)
{
return;
}
operation.Parameters ??= new List<OpenApiParameter>();
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
Array.Empty<string>()
}
}
};
}
}
The result is that padlocks appears only next to actions that a marked with [Authorize] and not marked with [AllowAnonymous] attributes:
I am developing web API in ASP.NET Core.
I am looking for a way for sending parameter beside authorization in swagger to send them in header
Add AddSecurityDefinition in options. https://gist.github.com/mbasaran/39734d645edcc258fcb507a710139b7d
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "api", Version = "v1" });
c.AddSecurityDefinition("oauth2", new ApiKeyScheme
{
Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
In = "header",
Name = "Authorization",
Type = "apiKey"
});
});
add parameters inside Available authorizations under Authorization input
I can get multiple login options to appear in SwaggerUI with code similar to
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("Google", new OAuth2Scheme
{
Description = "Google",
Type = "oauth2",
Flow = "implicit",
TokenUrl = "https://www.googleapis.com/oauth2/v3/token",
AuthorizationUrl = "https://accounts.google.com/o/oauth2/auth"
});
c.AddSecurityDefinition("Microsoft", new OAuth2Scheme
{
Description = "Microsoft",
Type = "oauth2",
Flow = "implicit",
TokenUrl = "blah",
AuthorizationUrl = "blah"
});
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
In = "header",
Name = "Authorization",
Type = "apiKey"
});
c.OperationFilter<SecurityRequirementsOperationFilter>();
and something similar to
app.UseSwaggerUI(c =>
{
c.OAuthClientId(this.Configuration["Authentication:Google:ClientId"]);
c.OAuthClientSecret(this.Configuration["Authentication:Google:ClientSecret"]);
c.OAuthAppName("blah");
c.OAuthScopeSeparator(string.Empty);
c.OAuthAdditionalQueryStringParams(new { audience = this.Configuration["Authentication:Google:ClientId"], scope = "openid profile email" });
c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});
If I have just one oauth provider configured it works fine. The problem is that both the Google and Microsoft login options will use the default ClientId and ClientSecret etc. declared in the UseSwaggerUI method.
Is there a way of supporting multiple login providers and their associated configuration in Swagger UI?