OAuth2 Authentication in OpenAPI Swagger ASP.NET Core
Today in this article, we shall discuss, how to add OAuth2 Authentication in OpenAPI Swagger ASP.NET Core 3.1 or .NET 5-based API application.
Today in this article, we will cover below aspects,
As we discussed in our last articles recently released Swagger V3.0 (OpenAPI v3.0 document specifications) documentation has brought a lot of improvements which include a few breaking changes too.
These differences often come as surprises until you are already aware of those details.
So, Let’s get started,
Create ASP.NET Core API application
Please create ASP.NET Core 3.1 or .NET 5 applications.
Add Swashbuckle.AspNetCore NuGet package
Please add the below Nuget package to your WebAPI using a Command prompt or PMC(package manager console)
PM> Install-Package Swashbuckle.AspNetCore -Version 5.6.3
Note - Please use the latest version if available
This NuGet package shall add all other required components as shown below and you need not have to add them explicitly,
- Swashbuckle.AspNetCore.SwaggerUI
- Swashbuckle.AspNetCore.Swagger
- Swashbuckle.AspNetCore.SwaggerGen
Using AddSecurityDefinition and AddSecurityRequirements
Add below two methods to your swagger middleware below,
- AddSecurityDefinition() and
- AddSecurityRequirement()
Both above methods let you define your API security by defining one or more security schemes like OAuth2 or JWT or Basic authentication scheme.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "TheCodeBuzzService", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("your-auth-url", UriKind.Relative),
Scopes = new Dictionary<string, string>
{
{ "readAccess", "Access read operations" },
{ "writeAccess", "Access write operations" }
}
}
}
});
});
Additionally please add OpenApiSecurityRequirement which lets you define the security scheme i.e OAuth2 that needs to be used.
Additionally, AddSecurityRequirement lets you enable the below schemes to Swagger (Open API) documentation which is discussed in the below articles in detail for your reference,
UseSwaggerUI in Configure() method
Please update UseSwaggerUI for using ClientId and secretes configuration as below,
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestService");
c.OAuthClientId("cleint-id");
c.OAuthClientSecret("client-secret");
c.OAuthRealm("client-realm");
c.OAuthAppName("OAuth-app");
c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
The generated swagger definition will look as below.
The ‘Authorize’ button will be displayed.
Please click on the Authorize Button and provide OAuth2 credentials.
That’s all, you are all set to use swagger with the OAuth2 authorization token.
The above OAuth2 scheme will be applied globally. OAuth2 scheme can be applied at the Operation level using Interface IOperationFilter.
Other references :
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Summary
In this post, we learned how to add OAuth2 Authentication to Swagger (OpenAPI) documentation in ASP.NET Core 3.1 or .NET 5 application. Swagger (OpenAPI) describes the standards and specifications for RESTFul API descriptions. Today we looked at enabling authentication schemes i.e OAuth2 scheme using the Swashbuckle tooling in the ASP.NET Core applications.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Nice article. I cannot get bearer token on ClientCredentials flow. When I track the Authorization header on filter, I get “bearer undefined”. Can you help me? [asp.net-core3.1]
Hey Developer,
Thanks for your feedback. There could be few possibilities for the issue. Please make sure to use the latest version swagger UI. Please make sure you are mapping the token format correctly(JSON format Mapping). Also, are you defining Oauth2 security schemes globally or at the Operation level?
I use the latest version of swagger-ui. I defined the Oauth2 security schemes on operation level. The problem is -> https://stackoverflow.com/questions/63341836/bearer-token-doesnot-pass-on-swagger
I able to create an access_token on same server succesfully but I can’t catch the Authorization token on my custom Authorization filter. It says “Bearer undefined”
Thanks for the additional details. I see you have added both global and local(as you mentioned) which might be confusing for swagger UI. If you only want to define Operation level OAuth2.. please refer the article as reference OAuth2 Authorize using IOperationFilter in Swagger(OpenAPI) ASP.NET Core
Hope this helps!
Thanks for the info. It’s very useful.
#1: Is it possible to show the [CustomAuthorize(new[] { Role.SuperAdmin, Role.Admin, Role.User })] on Swagger UI? Where [CustomAuthorize] drives from [Authorize] with Swagger-OAS3, CORE 3.1 project.
#2: In Swagger OAS3 used with Core 3.1, a lock image comes on endpoints even with no Authorization. How to hide the lock image only for specific action methods?
Hello Varun,
1. If you have a custom authentication scheme enabled in your API pipeline then yes should be able to enable authentication for the same additionally.
2. Lock image can be controlled at API level using Operation level filtering. I have discussed in the article OAuth2 Authorize using IOperationFilter in Swagger(OpenAPI) ASP.NET CoreOAuth2 Authorize using IOperationFilter in Swagger(OpenAPI) ASP.NET Core
Hope this helps.
Thanks !
Thanks , This was very helpful.