JWT Authentication In .NET Core Web API Project

Mert Savaş
Berkut Teknoloji
Published in
5 min readJan 8, 2022

Hello everyone! In this article, i’m going to show you how to implement JWT authentication in .NET Core Web API project. Have a nice reading ❤

What is JWT?

JSON Web Token (JWT) is an open standard defined in RFC 7519 based on JSON, which enables data exchange and verification between parties.

JSON Web Tokens generally consist of three parts; Header, Payload, and Signature. These parts are seperated by dots(“.”) and it looks like “aaa.bbb.ccc”.

Header specifies which algorithm will be used in the signature to be created. Example: {“alg”:”HS256", “typ”: “JWT”}

Payload contains previously given unique information between the parties. Example: {“username”: “admin”, “pass”: “123", “iat”:1422779638}

iat” is the information containing the creation time of the key.

Signature, on the other hand, is the structure that emerges when the header and payload are encoded with base64url and combined with a dot, and then encrypted with a secret key.

Finally, the token is formed by combining the three parts and encoding the signature with base64url.

Token looks like the following, eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Tokens can be decoded through web page called jwt.io

We talked about JWT in general terms. Let’s start to code our project now.

.NET Core JWT Authentication Project Structure

First, project requires two packages. We can install them using NuGet.

Configuration of JWT Settings in Startup.cs

The values of the model we created with the name JwtSettings come from the values we specified in the appsettings.json file. We generate our basic token definitions in the tokenValidationParameters object. We add these definitions and DefaultAuthenticateScheme to our service that will provide authentication. We determine which authenticate scheme the authorize methods will use and the part that invalid requests will return 401 by using the settings given in services.AddAuthorization() method.

Hmac-sha256 requires a key size of at least ‘128’ bits. However, size of SecurityKey can’t be less than 128 bits.

After writing the code block on the code block, we can call this method in the ConfigureServices method.

Finally, to use the Authorize tag, we need to add this usage in the Configure method.

Now, we are ready to code authentication part.

Controller

First of all, we create a list from the entity named User in UserController.

Then we define the configuration in the constructor to send it to the method that will provide authentication.

Login

Next is to write the Login method. This method allows anonymous requests. We specify the model containing Username and Password as our request model.

We are looking for user in userList with username and password in request. If there is a user, we create the token from the CreateToken method.

The codes we need to write in this method are in the picture below.

We send an email as a claim into the token for later use.

GetUser

This method is an authorize method. So it does not allow anonymous requests. The method expects a Bearer token in the request header.

We send the token from the header to the DecodeToken method, and if it is a valid token, we get the email that the token holds in the claim. Then we find the user in the userList with this email.

Snapshots

Conclusion

JWT provides a safe way of transmitting information between multiple parties in form of JSON object. It is a modern solution of authenticating user. By using JWT Authentication, we can secure our web services.

Today, I tried to share some information about JWT in .NET Core which I believe it may be helpful for some other developers. I hope you enjoyed it. You can take a look the repository on Github.

Good bye ❤

References

--

--