Swagger is a very useful feature in back-end. It provides a easy way to test API and gives lots of details of the interfaces. However, when most of the API are protected by authentication. How to get access to these APIs through swagger will be discussed here.

The content is:

  • set up swagger in startup file
  • configure authentication through Auth0
  • add authorization for swagger.

1. Set up swagger in startup file

Install the nuget package Swashbuckle.AspNetCore
Add the following code to ConfigureServices in Startup.cs

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "StudentSIMS", Version = "v1" });
});

Add the following to Configure:

app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My first API V1");
    c.RoutePrefix = string.Empty; // launch swagger from root
});

Then you should be greeted with a nice Swagger UI, when you run the program.

2. Configure authentication through Auth0

Here we use Auth0 to do authentication. Because how to setup an api in Auth0 is described very clear, we won't repeat it. You can check the quick start after you generate you API on Auth0.

// 1. Add Authentication Services
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = 	
                $"https://{Auth0Config.yourDomain}/"
            options.Audience = Auth0Config.yourApiIdentifier;
        });

Remember to enable authentication middleware app.UseAuthentication();

If you want to use permissions, you can add authorization policies in your code. For references, look up https://auth0.com/docs/quickstart/backend/aspnet-core-webapi/01-authorization