send more parameters in swagger Available authorizations pop up - asp.net-core

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

Related

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

Don't add Bearer verification

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:

Swashbuckle Swagger UI padlocks with OAS3 [duplicate]

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:

How swagger authentication works?

Hi I have developed swagger UI for my .net core web application. I have added authentication to it. I have registered two applications in my Azure AD. One for Swagger and one for Back end .Net core app. Below is my code.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = swaggerUIOptions.AuthorizationUrl,
TokenUrl = swaggerUIOptions.TokenUrl
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new[] { "readAccess", "writeAccess" } }
});
});
In the above code I am indicating type and flow. Also specifying AuthorizationUrl and token url. When coming to scopes, If I add scopes then that means my Swagger has access to added scopes or my back end api has access to those scopes? Then I have below code.
c.OAuthClientId(swaggerUIOptions.ClientId);
c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
c.OAuthAppName("Swagger");
c.OAuthAdditionalQueryStringParams(new { resource = azureActiveDirectoryOptions.ClientId });
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
When we develop swagger, We are getting access token for swagger app or back end app? Also I have c.OAuthRealm and passing my back end app client id. What this line of code do actually? Also when I add [Authorize] attribute in top of my API and then If i try to hit api directly It will not work. It will work only after authentication. So how Authorize attribute works exactly? Can someone help me to understand these things? Any help would be appreciated. Thanks
Regarding how to configure Swagger to authenticate against Azure AD, please refer to the following steps
Configure Azure AD for your web API. For more details, please refer to the document
a. Create Azure AD web api application
b. Expose API
c. Configure code
config file
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
"TenantId": "<your tenant id>"
},
Add following code in the Stratup.cs
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
Configure swagger. For more details, please refer to the blog.
a. Create Azure Web application
b. Configure API permissions. Regarding how to configure, you can refer to the document
c. code
Install SDK
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
Add the following code to Startup.cs in the ConfigureServices method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = $"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/oauth2/authorize",
Scopes = new Dictionary<string, string>
{
{ "user_impersonation", "Access API" }
}
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new[] { "user_impersonation" } }
});
});
Add the following code to the Configure method:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(Configuration["Swagger:ClientId"]);
c.OAuthClientSecret(Configuration["Swagger:ClientSecret"]);
c.OAuthRealm(Configuration["AzureAD:ClientId"]);
c.OAuthAppName("My API V1");
c.OAuthScopeSeparator(" ");
c.OAuthAdditionalQueryStringParams(new { resource = Configuration["AzureAD:ClientId"] });
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

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?