== blog.johanhellgren.se ==
...all things software development

JSON Web Tokens for people in a hurry

4 min read.

JSON Web Tokens (JWT) is a compact and self-contained way of securely sending information as a JSON object. The JSON object is digitally signed either with a secret (HMAC) or public/private key pair (RSA). JWT is an open standard (RFC7519)

The JSON object is structured into a header, a payload and a signature. (header.payload.signature)

Header = Type & Algorithm
Payload = Claims (reserved, public & private)
Signature = base64url encoded header, base64url encoded payload and a secret signed with the algorithm specified in the header (for example HS256)

How does it work?

The user signs in with an authentication server. The authentication server authenticates the user, creates a JSON Web Token and signs it with a shared secret (symmetric key). You can also sign the token with an asymmetric key i.e a public/private key pair (RSA). Finally the auth server returns the signed JWT to the user.

The user can now make requests to the application server(s). In each request the user sends the token in an HTTP Authorization header in the format: Bearer TOKEN. Depending on the user’s claims the user is authorized to do different things. The application servers validates the token using the shared secret, processes the request and sends a response.


Secure but not secret!

JSON Web Tokens is a compact and self-contained way of securely sending information as a JSON object. It is secure in the way that the application/resource server can, after validating the token, be sure that it is legitimate and untampered. It is base64 encoded which is not the same thing as encrypted, meaning that the client can easily decode the token and read it in plain text. If you don´t send it over https (ssl) so can also anyone eavesdropping on your communication.

This means a few things:

  • HTTPS is the way to go (as always….)
  • Don’t put sensitive information in JWT tokens!
  • If you really need to place sensitive information in the JWT tokens have a look at JSON Web Encryption (JWE).

.NET Core (and Node.js) demo with docker


With this demo you can spin up the following scenario with one command. You can then try it out with something like Postman and also try the included demo client (script).


Further reading

There is (of course) a lot more to JWT and token based authentication. Here are some resources I recommend:

Introduction to JWT
Understanding refresh tokens
JSON Web Tokens are made for Microservices
Use JWT The Right Way