Simple JWT Authentication with Swagger for .NET Web Api

To apply for the Shopify developer internship, applicants were challenged to build an image repository of some sort. To make the most of my time working on this project, I chose to explore a concepts I wasn’t too familiar with. This way, even if I don’t land an interview, I finish the project learning something useful.

Here’s the link to the challenge. I chose to build an API for an image repository using .NET 5 tried that met the following requirements:

  • Add single Image to repository
  • Private or public (permissions)
  • Secure uploading and fetching of images

I wanted to use JSON Web Tokens to authenticate the user and use SwaggerUI to test the endpoints. I spent hours reading blog posts and forums just to get this to work so I figure I’d pay it forward and summarize the steps needed so the next person trying to implement this could save some time. I will share the steps needed to

  1. Setup JWT Authentication
  2. Setup Swagger w/support for Authorization Header

Setup JWT Authentication

  1. Download the following packages
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerdotnet add package System.IdentityModel.Tokens.Jwt

2. Add issuer and secret key to appsettings.json

3. Generate JWT.

4. Register JWT Authentication Service

5. Add Authentication Middleware.

Order matters. This is necessary to use the [Authorize] attribute in the next step.

6. Create endpoint that requires authorization.

Note that in step 2, on line 17, we assign the username to the sub claim of the jwt but here we get the username from the ClaimTypes.NameIdentifier. This is due to mapping done by the JwtBearerAuthentication middleware. For more info, read this.

Voila! Now you have jwt authentication setup. Now let’s cover how we can test this using Swagger.

Setup Swagger w/ support for Authorization Header

  1. Register Swagger Generator Service

2. Add Swagger Middleware

Now when the API runs, Swagger UI will be served at the app’s root (http://localhost:<port>/).

3. Add Swagger Gen Security Options

This last step adds the Authorize button to the Swagger UI. There you enter the JWT token to add to request headers.

The repo for the project can be found here. Thanks for reading!

Learning things. Building things.