JWT Authentication using C#
After seeing some people struggle with authentications systems, I’ve decided to create JWT Authentication with C#.
You might be asking yourself what is JWT?
JWT is JSON Web Token.
It’s a token that only the server can generate, and can contain a payload of data.
A JWT payload can contain things like UserID or Email so that when the client sends you a JWT, you can be sure that it is issued by you.
There is plenty of information out there about JWT, we’re here to implement JWT and not explain what it is, let’s start the implementation.
Open your visual studio and create new console application project (or add new project to existing Web Api 2 \ MVC 5 project \ wherever you want).
Now open solution explorer > right click on the project > Manage Nuget Packages, change the selected tab to “Browse” and search for “System.IdentityModel.Tokens.Jwt”, choose the first package and install it.
Now we will open 2 folders.
- Models folder — The folder will contain all the classes that stores only information.
- Managers folder — This folder will store all the classes that makes the actual implementation of JWT..
Models folder will have 1 interface that will be called IAuthContainerModel and 1 class that will be called JWTContainerModel.
Managers folder will contain 1 interface that will be called IAuthService and 1 class that will be called JWTService.
Shall we start writing the code? :)
Let’s take a second to talk about our interfaces, we created interface called IAuthService, we will define all the basic methods for this interface, and we will define property “SecretKey”, we want to inject the secret key from outside the class and not from inside, the secret key should be in server configurations.
Now let’s talk about IAuthContainerModel interface, we want the most basic things in this interface which will be required by any authentication service.
Time to start working on the implementation, Let’s start with the simple implementation of the model JWTContainerModel, firstable we must inherit the interface IAuthContainerModel.
- We will set default values for “ExpireMinutes” which will be 10080 minutes which is 7 days token expiration date.
- We will use default encryption algorithm for “SecurityAlgorithm” which will be “HmacSha256Signature” and we get it from SecurityAlgorithms class.
- For now I will set “SecretKey” value, it’s important to get the secret key from server configurations! putting the secret key as hard coded inside your class is really bad practice!
It’s time to implement JWTService, firstable we’ll inherit the interface IAuthService.
We will start by creating two private methods GetSymmetricSecurityKey and GetTokenValidationParameters, Their implementation are pretty straight forward.
- The method GetSymmetricSecurityKey() takes the secret key and converts it to byte array and returns new SecurityKey class which sits in “Microsoft.IdentityModel.Tokens” namespace.
- The method GetTokenValidationParameters() creates new instance of TokenValidationParameters model which sits in “Microsoft.IdentityModel.Tokens” namespace.
The namespace “Microsoft.IdentityModel.Tokens” comes from the nuget package we installed at the begging of this tutorial.
Let’s implement constructor, which is also pretty straight forward.
And now the interesting part for the basic methods that actually creates and validates our token.
We’ll start with the method “bool IsTokenValid(string token)”, this method takes the required token and returns true in case the token is valid, otherwise it will return false.
Important note: If the token is not valid or the date has been expired the method will throw an exception.
Let’s check the method “string GenerateToken(IAuthContainerModel model)”, this method should receive the basic parameters for the user and sign new token for the client.
We’ll take the claims, the security algorithm, and expired time and we will create instance of SecurityTokenDescriptor class that sits in “Microsoft.IdentityModel.Tokens” namespace and then we will get new token.
Now the last method “IEnumerable<Claim> GetTokenClaims(string token)”, as you know JWT stores data inside his body, we can get this data by the token.
let’s create simple Main to run our project and see that everything works fine :)
Let’s create simple function to get for us JWTContainerModel and the claims we want.
Our main method should be like this, I will say it again, the secret key should be imported from server/cloud configurations!