Authenticate Swagger UI against Azure Active Directory in ASP.NET Core Web API Project

DINESH BALANI
3 min readJul 2, 2020

--

Adding Swagger UI to your protected .net core web apis

NSwag is Swagger UI generator library for .net core web application. If you are developing a solution that will just expose APIs or even a web application with its own frontend, adding Swagger UI will make it easy for backend developers to develop and test their APIs as well as for getting started your customers to understand and consumer your web APIs.

You can find complete solution at https://github.com/dineshbalani/Swagger-AzureAd-WebApi-Authentication

Register your application in Azure Portal

Add Your Application Name
Add Redirect URI:- https://localhost:{port}/oauth2-redirect.html

Add Scopes to your application
Add Application ID URI: api://{ApplciationID}
Add Scope: api://{ApplicationId}/user_impersonation
A scope can be anything instead of user_impersonation, Scopes define the permissions for your consumers, for some consumers you may want to give them just read access, APIs defined within a scope, consumers are given access to these scopes to perform limited operations

Creating a Web API Project in .net core :-

Install libraries: In the package manager console, execute the following command

Install-Package NSwag.AspNetCore
Install-Package Microsoft.AspNetCore.Authentication
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

In AppSettings.json , add AzureAd Configurations

In Startup.cs

Add a private function to generate SwaggerUI

Modify Configure function to add swagger ui to the app

Modify ConfigureServices function to add bearer authentication and call AddSwagger() function, created in the first step

Test the Authorization

You can change your project properties to launch swagger directly upon running the application by Right-Click project -> Go to properties -> Go to debug and add swagger in Launch Browser text box.

This is an optional step to launch swagger automatically when you run the application

Alternatively you can run the application and browse to https://localhost:44312/swagger/ and click on authorize button, The client id should be pre filled

Once the sign process is completed a bearer token is returned

And now this bearer token is added to all the api calls with [Authorize] attribute on controller functions

You can find complete solution at https://github.com/dineshbalani/Swagger-AzureAd-WebApi-Authentication

References:
https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-nswag?view=aspnetcore-3.0&tabs=visual-studio

--

--