Don't add Bearer verification - asp.net-core

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:

Related

Validate JWT using swagger .net core 6 API

I am trying to authorize a token using swagger. See the image below. My issue is when I type in an invalid token, I don't get any errors or anything.
Below is the API
[Authorize]
[HttpGet("GetUsers")]
public IEnumerable<CountryOutputDto> GetCountriesList()
{
return _countryAppService.GetCountries();
}
Below is are my settings
// Add Authencation
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWTToken_Auth_API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
"JsonWebTokenKeys": {
"ValidateIssuerSigningKey": true,
"IssuerSigningKey": "64A63153-11C1-4919-9133-EFAF99A9B456",
"ValidateIssuer": false,
"ValidIssuer": "https://localhost:8100",
"ValidateAudience": false,
"ValidAudience": "https://localhost:8100",
"RequireExpirationTime": true,
"ValidateLifetime": true
}

Enabling authentication in swagger

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

Curl appending authorisation header but controller still 401

I am using the swagger gen ui and I am using the following settings and following this GitHub resource.
This seems to be a known issue with swagger according to GitHub, I am using a jwt barrer based token. https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1425
I have setup my swagger gen as follows
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Manager - Running Buddies", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}, new List<string>()
}
});
});
curl -X GET "https://localhost:44396/api/BmiInformations" -H "accept:
text/plain" -H "Authorization:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTAxOTMyNzQsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0Mzk2LyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0Mzk2LyJ9.cbePeT9RJprvTWyQECiUCaoqjc25eFKtf7jh5DwOnU0"
But Still I am getting 401 unauthorised I am using a JWT based token that is valid.
private string BuildToken(LoginModel login) {
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtToken:SecretKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken token;
token = new JwtSecurityToken(_config["JwtToken:Issuer"],
_config["JwtToken:Issuer"], expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
private UserModel Authenticate(LoginModel login) {
UserModel user = null;
//var result = await _signInManager.PasswordSignInAsync(, lockoutOnFailure: false);
if (login.Username == "mario" && login.Password == "secret") {
user = new UserModel { UserName = "Mario Rossi", Email = "mario.rossi#domain.com" };
}
return user;
}
This is how am building up my filter.
public class AddAuthHeaderOperationFilter : IOperationFilter {
public void Apply(OpenApiOperation operation, OperationFilterContext context) {
if (operation.Security == null)
operation.Security = new List<OpenApiSecurityRequirement>();
var scheme = new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearer" } };
operation.Security.Add(new OpenApiSecurityRequirement {
[scheme] = new List<string>()
});
}
I have added to after my barrer bit. But its still not showing the word barrer
services.AddDbContext<AppManagerDL.AppManagerDBContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Manager - Running Buddies", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer"
});
c.OperationFilter<AddAuthHeaderOperationFilter>();
Edit 4
Ok So now I have it showing Barrer correctly in the curl but its now saying the signature is invalid even though its getting the correct one from my appsettings.
curl -X GET "https://localhost:44396/api/BmiInformations" -H "accept:
text/plain" -H "Authorization: Bearer
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTAxOTc0MTcsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0Mzk2LyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0Mzk2LyJ9.fLWxG1bRX6yCTqFe8XZbgL6Lh1RNcmVFX-636ZvqhNg"
My Settings in start up as as follows.
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<AppManagerDL.AppManagerDBContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Manager - Running Buddies", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference{
Id = "Bearer", //The name of the previously defined security scheme.
Type = ReferenceType.SecurityScheme
}
},new List<string>()
}
});
The Exact error I am now getting is.
date: Sat, 23 May 2020 01:04:11 GMT server: Microsoft-IIS/10.0
status: 401 www-authenticate: Bearer error="invalid_token",
error_description="The signature is invalid" x-powered-by: ASP.NET
Try replacing your current security definition with this :
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Scheme = "bearer",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT"
});

Swashbuckle UI not displaying Security Scheme Description OAuth2

I'm trying to add a security scheme to my swagger UI page and it's getting added successfully, however, my description is not rendering or being shown at all on the UI page. I want it to display successfully since I will switch this code to be an IOperationFilter and have the description vary by endpoint. For now, though, this is my code for AddSwaggerGen:
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "MyAPI",
Version = "v1"
});
options.EnableAnnotations(true);
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "This is my description that's not showing", // I want this to display on the UI
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
ClientCredentials = new OpenApiOAuthFlow
{
TokenUrl = new Uri("/token", UriKind.Relative)
}
}
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
});
This is my available authorizations that's generated in the UI:
I would assume my description should go where it's describing scopes like it does for JWT. Am I missing a configuration? I am using Swashbuckle.AspNetCore 5.0.0
This is a known issue with Swagger UI:
https://github.com/swagger-api/swagger-ui/issues/5230

Is there support for multiple oauth2 authentication login providers in SwaggerUI?

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?