Author : MD TAREQ HASSAN | Updated : 2020/05/31

What is Json Web Token

JWT parser

See: dev-handy-sites#web-security

When should you use JSON Web Tokens?

Structure and format

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

Therefore, a JWT typically looks like the following: xxxxx.yyyyy.zzzzz

Structure

JSON Web Tokens Structure

Details: https://jwt.io/introduction/

How do JSON Web Tokens work?

Courtesy: https://jwt.io

In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like: Authorization: Bearer <token>

his can be, in certain cases, a stateless authorization mechanism. The server’s protected routes will check for a valid JWT in the Authorization header, and if it’s present, the user will be allowed to access protected resources

Producing a token

var token = new JWTSecurityToken(
	issuer: "http://myIssuer",
	audience: "http://myResource",
	claims: GetClaims(),
	signingCredentials: GetKey(),
	validFrom: DateTime.UtcNow,
	validTo: DateTime.UtcNow.AddHours(1));

// serialize
var tokenString = new JWTSecurityTokenHandler().WriteToken(token);

Consuming a token

var token = new JWTSecurityToken(tokenString);

var validationParams = new TokenValidationParameters
{
	ValidIssuer = "http://myIssuer",
	AllowedAudience = "http://myResource",
	SigningToken = GetSigningKey()
};

var handler = new JWTSecurityTokenHandler();
var principal = handler.ValidateToken(token, validationParams);