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

What is Json Web Token

  • 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
  • JWTs are credentials, which can grant access to resources
  • JSON encoded
  • symmetric and asymmetric signatures (HMACSHA256-384, ECDSA, RSA)
  • symmetric and asymmetric encryption (RSA, AES/CGM)
  • If the token is sent in the Authorization header, Cross-Origin Resource Sharing (CORS) won’t be an issue as it doesn’t use cookies
  • JWT is easy to
    • create
    • transmit
    • parse
    • validate

JWT parser

See: dev-handy-sites#web-security

When should you use JSON Web Tokens?

  • Authorization
  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties

Structure and format

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

  • Header
  • Payload
  • Signature

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


  • Header
    • metadata
    • algorithms & keys used
  • Claims
    • Issuer (iss)
    • Audience (aud)
    • IssuedAt (iat)
    • Expiration (exp)
    • Subject (sub)
    • …and application defined claims

JSON Web Tokens Structure


How do JSON Web Tokens work?


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

  • Retrieve serialized token: from HTTP header, query string etc…
  • Validate token and turn into claims
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);