This post is about documenting OAuth 2 protected ASP.NET Core Web API using Swashbuckle. Last post - Securing Your Web API Using Azure Active Directory I wrote about securing web api with Azure Active Directory. In ASP.NET Core Web API, Open API will be enabled by default. To enable OAuth2 authentication, first we need to write the following code. I this code we are adding a SecurityDefinition with OAuth2 type. And also configuring Authentication URL, Token URL and Scopes.
This will display the Authorize button, like this.
Click on the Authorize button will display Available authorizations, like the following.
You need to provide the Client Id and select the scopes. Once you complete it click on
Authorize button, which will open the Microsoft AD authentication page, but you might get an error like this -
AADSTS700051: response_type 'token' is not enabled for the application.
It is because
Access tokens and
ID tokens is not enabled. You can enable it from Authentication menu.
Select Access tokens and ID Tokens and save the changes. Next you will get another error - because we didn’t added the callback URL. We need to add the following URL. -
https://localhost:5001/oauth2-redirect.html - if you’re using Visual Studio instead of 5001 use the port. You can add it under Authentication, Web and Redirect URIs. And save it. Next click on Authorize, you can login, but it we won’t get the proper token. It is because we don’t have Client Secret configured and we didn’t configured the authentication for controllers and action methods.
To enable this you need add the following code.
Which will show the lock sign near action method, clicking on them show the same dialog.
And finally add the following code in
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 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 next password. And finally it will show the permission dialog like this.
Click on the Accept button and continue. It will authenticate and returns a token. Then the open lock symbol changed to closed lock symbol.
Clicking on the symbol again will show the authenticated dialog.
So we have completed the OAuth2 integrated to ASP.NET Core Web API. Similar way you can integrate other authentication protocols.
Happy Programming :)