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.

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
- c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme {
- Type = SecuritySchemeType.OAuth2,
- Flows = new OpenApiOAuthFlows() {
- Implicit = new OpenApiOAuthFlow() {
- AuthorizationUrl = new Uri("https://login.microsoftonline.com/*Tenant ID*/oauth2/v2.0/authorize"),
- TokenUrl = new Uri("https://login.microsoftonline.com/*Tenant ID*/oauth2/v2.0/token"),
- Scopes = new Dictionary < string, string > {
- {
- "*Scope*",
- "Reads the Weather forecast"
- }
- }
- }
- }
- });
This will enable the Authorize button in Swagger UI,

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,




Johnny OlsenPosted Oct 24, 2021, 4:27 PM
Hi Jay, I'm a newbie to oauth2 but I downloaded the code and try to authenticate but I must have missed something. Where I start to get confused is where the page is with the header Azure_auth |Authentication.Where does it come from and a red frame around some texts and the red text "enable these 2 options". Can you help me , please . Regards Johnny
Johnny OlsenPosted Oct 24, 2021, 4:21 PM
Hi Jay, I'm a newbie to oauth2 but I downloaded the code and try to authenticate but I must have missed something.
Shashank SPosted Aug 12, 2021, 2:09 PM
Www-authenticate: Bearer error="invalid_token"error_description="The audience '' is invalid"
Neil BroomfieldPosted Jul 9, 2021, 4:21 PM
I just get this error when it tried to hit the token endpoint..."The endpoint only accepts POST, OPTIONS requests. Received a GET request." :-(
Vinay AyinapurapuPosted Jun 3, 2021, 10:32 PM
Excellent article.
Jay Krishna ReddyPosted Jun 2, 2021, 8:06 AM
Thanks for your feedback Hamid Khan
Hamid KhanPosted Jun 2, 2021, 7:51 AM
Very nice article