🔐 Enable OAuth 2 Authorization Using Azure AD And Swagger In .Net 5.0

In this article, we will learn how to protect our .Net core web APIs by using Azure Active Directory, OAuth2, and Swagger. As we all know that swagger is in-built configured in the .Net 5.0 template so that we don't need to take care of documenting our APIs in this latest .Net 5.0. 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0
In the last article - Enable Azure AD Authentication using .Net 5.0 Web API I wrote about Azure Active Directory setup and securing our APIs using Azure AD.
 
So in this article, I will show how we can add extra setup in order to authenticate the APIs using swagger. After setting up the Azure AD we need to add the code for OAuth 2 Authentication.
 
We are adding a SecurityDefinition with OAuth2 type. And also configuring Authentication URL, Token URL, and Scopes. 
 
Startup.cs
  1. c.AddSecurityDefinition("oauth2"new OpenApiSecurityScheme {  
  2.     Type = SecuritySchemeType.OAuth2,  
  3.         Flows = new OpenApiOAuthFlows() {  
  4.             Implicit = new OpenApiOAuthFlow() {  
  5.                 AuthorizationUrl = new Uri("https://login.microsoftonline.com/*Tenant ID*/oauth2/v2.0/authorize"),  
  6.                     TokenUrl = new Uri("https://login.microsoftonline.com/*Tenant ID*/oauth2/v2.0/token"),  
  7.                     Scopes = new Dictionary < stringstring > {  
  8.                         {  
  9.                             "*Scope*",  
  10.                             "Reads the Weather forecast"  
  11.                         }  
  12.                     }  
  13.             }  
  14.         }  
  15. });   
This will enable the Authorize button in Swagger UI,
 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0
 
Once you click on the Authorize option we need to provide the ClientID and also select the scopes.
 
Once we complete it then click on the Authorize button, which will open the Microsoft Active Directory Authentication page, but we might get an error because we need to grant access to Access tokens and Id tokens and we can enable it from Authentication Menu,
 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0
 
Next, we need to configure the Redirect URL which it will redirect after successful Authentication https://localhost:*PortNo*/swagger/oauth2-redirect.html
 
You can add it under the Authentication, Web, Redirect URLs and save it.
 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0
 
We are adding the security requirement for OAuth2 Setup in the Swagger configuration,
 
Startup.cs
  1. c.AddSecurityRequirement(new OpenApiSecurityRequirement() {  
  2.     {  
  3.         new OpenApiSecurityScheme {  
  4.             Reference = new OpenApiReference {  
  5.                     Type = ReferenceType.SecurityScheme,  
  6.                         Id = "oauth2"  
  7.                 },  
  8.                 Scheme = "oauth2",  
  9.                 Name = "oauth2",  
  10.                 In = ParameterLocation.Header  
  11.         },  
  12.         new List < string > ()  
  13.     }  
  14. });   
Finally, we need to add the ClientID and client secret key in Swagger UI in order to validate the credentials. 
 
Startup.cs
  1. app.UseSwaggerUI(c => {  
  2.     c.SwaggerEndpoint("/swagger/v1/swagger.json""AzureAD_OAuth_API v1");  
  3.     //c.RoutePrefix = string.Empty;    
  4.     c.OAuthClientId("Client Id");  
  5.     c.OAuthClientSecret("Client Secret Key");  
  6.     c.OAuthUseBasicAuthenticationWithAccessCodeGrant();  
  7. });   
Now we have completed the configuration.
 
Run the application and you will be able to see the authentication icons on the UI and clicking on them will show the authentication dialog with client Id pre-populated.
 
Click on Authorize, which will open the Microsoft Sign-in dialog. First, you need to provide the email and the next password. And finally, it will show the permission dialog like this.
 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0 
 
Add the credentials to authenticate and get the Access token. Then the open lock symbol changes to a Closed lock symbol,
 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0 
 
Output 
 
🔐 Enable OAuth 2 Authorization using Azure AD and Swagger in .Net 5.0
 
So this is how we can easily integrate OAuth2 in.Net Core web API, Similar way we can integrate other authentication protocols.
 
Source Code - GitHub Repo
 
Thank you for reading, please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.
 
Keep learning ....!