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 API application (originally written for ASP.NET Core 3.1 and .NET 5; current versions are .NET 10 with Swashbuckle.AspNetCore 10.x).
Updated November 2026: a .NET 10 and Swashbuckle 10 migration section, a PKCE and troubleshooting section, and an FAQ.
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 an ASP.NET Core Web API application. The steps below were written for 3.1 and .NET 5; on .NET 9 and later the default template no longer includes Swashbuckle, so add it yourself.

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 !!
Troubleshooting Swagger OAuth2 Login Failures
Most Swagger OAuth2 failures come from a mismatch between what Swagger UI sends and what the identity provider or your API expects. Check the client registration first, then the token the API receives, then whether the header is sent at all.
Is the Swagger UI client registered correctly?
Register Swagger UI in your identity provider as a public client, because a browser can’t keep a secret. Add /swagger/oauth2-redirect.html on your API’s host as an allowed redirect URI, and allow only the scopes the client needs.
Note: A redirect URI is like a delivery address on file with a courier. If the address on the parcel differs by even one character, the courier refuses to deliver it.
A redirect URI mismatch is the most common failure. Compare scheme, host, port and path exactly, including http versus https and a local port that changes between launches.
Why does login fail or return 401 afterwards?
Work through these causes in order:
- CORS on the token endpoint: Swagger UI calls the token endpoint from the browser, so the provider must allow your API’s origin. A blocked request shows up in the browser console, not in your API logs.
- Wrong scopes: A scope in the Swagger definition that the client isn’t allowed to request makes the provider reject the sign-in. Make the names match the provider’s registration exactly.
- Audience mismatch: If login succeeds but every call returns 401, the token’s
audclaim probably doesn’t match the audience your JWT bearer validation expects. Decode the token and compare it with your API configuration.
Remember that a security scheme only describes how callers authenticate. Your API still needs its own token validation.
Why is no Authorization header sent?
If the Authorize button appears but requests carry no header, you likely have a security definition without a security requirement. AddSecurityDefinition only registers the scheme. AddSecurityRequirement declares which operations use it, so you need both.
Should Swagger UI be available in production?
Limit Swagger UI and the OpenAPI endpoint to the Development environment, or protect them. Microsoft’s sample does this for MapOpenApi to reduce the risk of exposing sensitive information. The same rule applies to Swagger UI, ReDoc and Scalar.
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 (2026) 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.