Mark As Completed Discussion

Token-based authentication

Token-based authentication requires more manual setup than the cookie-based one, but it often can be used to overcome the shortcomings of the cookie-based approach.

In this type of authentication, the server verifies the user's credentials and sends back an encrypted token to the browser, where it is stored and can be added as an authorization header for the subsequent requests.

There are several unique approaches and implementations of token-based authentication. But for the purposes of this tutorial, we are going to give an example of the implementation of JWT (JSON Web Token). The token is generally sent as an addition Authorization header in the form of Bearer {JWT}, but can additionally be sent in the body of a POST request or even as a query parameter.

We can say there are four main steps in this approach:

Token-based authentication

The jwt.io website can be used to parse the JWT token information, and for encoding or decoding tokens to test.

The anatomy of a JWT token consists of three parts separated by dots. These parts include the header, the payload, and its signature respectively in the format header.payload.signature.

SNIPPET
1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

If we use the jwt.io website to decode this token, this is the information we would get:

Header - algorithm and token type

SNIPPET
1{
2 "alg": "HS256",
3 "typ": "JWT"
4}

Payload data

SNIPPET
1{
2 "sub": "1234567890",
3 "name": "John Doe",
4 "iat": 1516239022
5}

Verify signature

SNIPPET
1HMACSHA256(
2  base64UrlEncode(header) + "." +
3  base64UrlEncode(payload),
4)