Authentication

All You Need to Know About JWT Authentication

All You Need to Know About JWT Authentication

JSON Web Token (JWT) is a standard for user authentication (RFC 7519), enabling secure information exchange online as a JSON object. JWT comprises three parts: the header, detailing the encryption algorithm; the payload, containing ‘claims’ or transmitted information; and the signature, used for verifying the data’s authenticity. It’s self-contained and digitally signed, so the recipient can trust the transmitted information. 

Below are JWT authentication’s main use cases, how it works, and best practices for implementing it.

What Is JWT Authentication?

A JWT is a JSON-encoded representation of a claim, which may be transferred between two entities. The claim is signed digitally by the token’s issuer. The recipient party of this token may use this digital signature to demonstrate ownership in the future. 

Signed tokens can be used for authentication by verifying the genuineness of the claims they are attached to. Encrypted tokens, on the other hand, conceal those claims. When tokens are signed via private/public keys, a signature also guarantees that the party with the private key alone has signed it.

The following are scenarios in which JWT may be helpful:

  • Authentication – This is the most prevalent scenario. After the user has logged in, every following request will feature the JWT, letting the user access services, routes and resources allowed with the token. Single Sign On (SSO) commonly uses JWT today, because of its minimal overhead and because it works across domains.
  • Information Exchange – Because a JWT is signed, parties can use it to exchange data securely. For instance, a JWT may be signed using private/public key pairs to confirm the sender’s identity. Because the signature is computed from the payload and the header, the recipient can verify that the content has not been altered. 

Read our detailed guide about Authentication vs Authorization

JWT Components

JWTs have three main components: signature, payload, and header. A dot (.) separates each part.  

1. JWT Header

The header names the algorithm used to create the signature. The decoded form of the header should look like:  

<code>{
 “alg”: “HS256”,
 “typ”: “JWT”
}</code>

In the example above, HS256 is the hashing algorithm HMAC SHA-256, used to produce the signature.

2. JWT Payload

All JWT authentication claims are retained here. Claims are used to authenticate the party that receives the token. For instance, a server may set a claim that says ‘isAdmin: true’ and give it to an administrator once they log into the application. The administrator can then use this token in all subsequent requests they send to a server to verify their identity. 

The decoded payload in the JWT example is:  

<strong><code>{
 “sub”: “1234567890”,
 “name”: “Jill Smith”,
 “iat”: 1516239022
}</code></strong>

The “name” field identifies the person the token was given to. The “sub” and “iat” are instances of registered claims and are shortened forms of “subject” and “issued at”.

3. JWT Signature

The signature is derived from the header and payload fields. To create it: 

  1. Join the base64url encoded representation of header and payload with a dot (.)
    base64UrlEncode(header) + “.” + base64UrlEncode(payload)
  2. Hash the data above with a secret-key only revealed to the server that issues the token. The hashing algorithm is the algorithm described within the header.
    hash_value = hash([base64UrlEncode(header) + “.” + base64UrlEncode(payload)], secret-key)
  3. Base64Url encode the hash value from the previous step.
    Signature = base64UrlEncode(hash_value)

Since only the server knows the “secret-key”, only the server can issue new tokens with an authentic signature. Users can’t forge a token with a valid signature, because that requires knowledge of the “secret-key.”  JWTs are used in different authentication mechanisms and are generally passed in the “authorization” header when a user submits a request to the client. 

When Should You Not Use JSON Web Tokens?

The use of JWTs for session tokens may be appealing at first, given that: 

  • You can retain any sort of user details on the client
  • The server can trust the client as the JWT is signed, and there is no need to call the database to retrieve the information you stored in the JWT
  • You don’t have to coordinate sessions in a central database when you reach the inevitable issue of horizontal scaling

However, JSON Web Tokens shouldn’t be used as session tokens by default, for these reasons: 

  •  A JWT has a large range of features and a wide scope, which raises the potential for errors, either through users or library authors. 
  • You can’t get rid of a JWT at the end of a session, because it is self-contained and no one authority can deem it invalid. JWTs are also large. When used with cookies, this means a lot of overhead per request. 
  • Implementing and using JWTs has a significant cost. They are sent with each request to the server, which always costs more than server-side sessions. 
  • While there are less security risks with JWT when compared to Hypertext Transfer Protocol Secure (HTTPS), a JWT can still be intercepted and the information is deciphered, revealing the user’s information. 

If you have a database for your app, a better option is to use a sessions table and the consistent sessions offered by the server-side framework you select.

Related content: Magic Links

JWT Authentication Best Practices

Consider applying the following practices when using JSON Web Tokens.

1. Validate Tokens

Always validate incoming JWTs, even within an internal network where the Authorization Server, Resource Server, and Client are offline. Don’t rely on your environment settings for security. If using a public domain, you have to deal with a different threat model, which requires extensive security measures. Validating tokens from the start protects you from attempts to breach your network.

The only instance when you don’t need to check a token’s signature is when you first receive it in the response from the Authorization Server’s token endpoint. 

2. Check the Audience Claim

The Resource Server should always check a token’s audience claim against a whitelist. Any request with a token intended for a different audience should be rejected. Access tokens should include the URL of the API they were issued for. ID tokens must include the client ID in their aud claims. Tokens must be decoded for the client to be able to use the data they contain.

Tokens should be passed on to the intended audience only to mitigate attack vectors that use a legitimate server to pivot to another server. 

3. Ensure That All Tokens Are Used Correctly

JWTs can serve as ID tokens or access tokens. You need to distinguish the different intended uses of each token. Don’t accept an unintended use for a JWT, such as an access token being used as an ID token. To ensure tokens are used correctly, check their scope (ID tokens don’t have any). Check the different audience claim values to determine the token type. 

You may use the value of that claim to verify the token type. Set a purpose claim for tokens via the Curity Identity Server. 

4. Avoid Symmetric Signing

Avoid symmetric signing where you can. Symmetric keys require all parties to know the secret, which makes it harder to protect. It is also difficult to know who has signed the keys. With asymmetric keys, you know that the JWT was signed by the individual with the private key. With symmetric signing, anyone who can access the secret can sign the tokens.

There are very few use cases where you must use symmetric signing today. If you do, it’s best to use secrets to increase security.

5. Watch Out for XSS and CSRF Attacks

Where you keep a JWT in the browser decides which attacks it is exposed to. Anything in localStorage or sessionStorage can be read by any script on the page, so a single cross-site scripting (XSS) flaw is enough to steal the token. OWASP advises against keeping session identifiers in local storage for this reason.

The safer default for browser apps is a cookie with these attributes:

  • HttpOnly: JavaScript can’t read the cookie, so an XSS flaw can’t copy the token. The browser still sends it with requests to your API.
  • Secure: the browser only sends the cookie over HTTPS.
  • SameSite: controls whether the cookie is sent with cross-site requests. Strict never sends it cross-site. Lax sends it only on top-level navigations that use a safe method such as GET, and not on cross-site POST, fetch or embedded requests. None sends it everywhere and requires Secure. Many browsers treat a cookie with no SameSite value as Lax.

Cookies bring back cross-site request forgery (CSRF), because the browser attaches them automatically. SameSite=Lax or Strict blocks most CSRF; an anti-CSRF token on state-changing requests covers the rest (see the OWASP CSRF cheat sheet).

Related: Password Authentication is Becoming Outdated 

JWT Authentication with Frontegg

Frontegg’s authentication infrastructure is based on JWT by design. Our JWTs are implemented to be fully compliant with common protocols like OpenID Connect 1.0 (OIDC) and OAuth2.

Frontegg’s authentication also lets you integrate your app with third parties using our well-known JSON Web Key Set (JWKS) endpoints, along with the public certificate and refresh tokens that come with the JWT mechanism.

With Frontegg, it takes five minutes to make your application fully JWT protected. Contact us to get started.