What is JWT(Json Web Token) and How to Implement JWT Auth in ASP.NET Core?

Fatih Ünlü
5 min readMay 29, 2021

--

Authentication is the most important part of any web application. Server-based and cookie-based authentications are the easiest way to authentication. However, because of the rising popularity of single-page applications or restful API services authorization needs a better approach. JWT is the best solution to authentication problems for APIs.

Before we get into this JSON Web Token Example, what exactly is a JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

A JWT is represented as a sequence of base64url encoded values that are separated by period characters.
There are 3 main parts and separated by “.”.

For example:
firstpart.secondpart.thirdpart

  1. the first part has represented the header,
  2. the second part has represented the payload,
  3. the third part has represented the signature.

The header contains the type of the token(typ) and the name of the algorithm that used to make the signature(alg).
According to the image above typ: ‘JWT’, alg: ‘HS256’
The header part is encoded(base64) with these type and algorithm.
The second part is the payload. A payload is a JSON object of data which we can put whatever we want in it. For example { Id: 4, IsAdmin: true }
This part also gets encoded with base64.
The third part is the signature part. This part is a hash of the encoded header, the encoded payload, and a secret that you provide using the algorithm defined in the header.

After these actions, our token is like aaaaaaa.bbbbbb.ccccc

Note: We shouldn’t put private(sensitive) information in the header and payload parts because these parts can be easily decoded on the frontend or backend.

How to use this? We use this token for every request(except authentication requests) to the server. Like (“Authorization: Bearer aaaaaaa.bbbbbb.ccccc”)

When the server sees the token that we sent the request, it decodes and compares the signature with the secret it has stored which would have been used to generate the token in the first place.
If tokens are matches and valid, then the request is authenticated and it responds with data otherwise, it sends an error message or whatever you want.

In this part, I am going to show you how to implement the ASP.NET Core Web API app using JWT and SPA with Angular which uses JWT to authenticate.

First, we install packages for authentication; JWT and JwtBearer, for identity and ef core Identity.EntityFrameworkCore, for database provider SqlLite.

Requests have a token which authenticates, then the server reads the token and validates it as we mentioned above. To configure JWT we set every setting in the ConfigureServices() method in the Startup file. Then we insert auth middlewares with UseAuthentication and UseAuthorization in the Configure() method.

JWT settings

There are lots of options about the user in here, we can change the requirements to sign-up or login(require digit, length, unique email, etc)

With TokenValidationParameters we can configure how to validate our token, for example;

  • ValidateIssuerSigninKey,
  • IssuerSigingKey,
  • ValidateAudience,
  • ValidateIssuer
  • ValidateLifeTime,

Let’s Create AuthController:

Before we finish the backend side we have to choose which controllers we want to authorize. In WeatherForecastController we add the [Authorize] attribute, so when we want to reach weatherforecast controller (http://localhost5000/api/weatherforecast) from other platforms we have to send token which is correct and valid. The backend side is done. Let’s make the front-end part and use the weatherforecast controller.

The Front-end part

We implement login and register services as we mentioned above. Now we’re gonna create SPA with Angular in the ClientApp folder.

To authenticate a user, we need Auth Service. In this service, we implement login and register services.

When a registered user login successfully, we get the token from the server. After we get that token, we store it in localStorage in the web browsers. Now we must use this token for every request we make in the SPA.

Fetch-data page makes an http request to get weather forecast data. Normally, we need to add the token to HttpHeader, but we won’t. Instead of adding each HTTP request manually, we will configure it in the base with auth0/angular-jwt library.

With JwtModule we include token to http Header for every http request that we make. We can set a blacklist(disallowedRoutes) for not to include token and whitelist(allowedDomains) to include token requests. As you see below we added auth route in the disallowedRoutes array because we don’t need authorization in the authorization controller.

I developed this project on GitHub, you can see it with this link below;
https://github.com/fatihunlu/JWTDemo

Conclusion

That is all :) With this article, you can easily create an ASP.Net Core web application with JWT and use it on SPA.
Hope it helps.

Thanks for reading.

References

--

--

No responses yet