Original link: learnku.com/laravel/t/4… For discussion, head to the professional Laravel developer forum: learnku.com/Laravel

You’ve already heard that JSON Web Tokens (JWT) are the latest technology being used to secure apis.

As with most security topics, it’s important to understand how it works (up to a point) if you’re going to use it. The problem is that most of the explanations for JWT are technical, which is a pain in the neck.

Let’s see if I can explain how JWT can protect your API without attracting your attention!

API authentication

** Some API resources require restricted access **. For example, we don’t want one user to be able to change another user’s password.

That’s why we secure certain resources so that the user provides his ID and password before allowing access — in other words, we authenticate them.

The difficulty with protecting HTTP apis is that requests are stateless — the API has no way of knowing if two requests are coming from the same user.

So why not ask the user to provide their ID and password every time the API is called? Just because it would be a horrible user experience.

JSON Web Token

What we need is a way to allow users to provide their credentials only once, and then to be identified in a different way by the server on subsequent requests.

Several systems have been designed for this, and the latest standard is JSON Web Token.

Here’s an excellent article on the subject, which is a good metaphor for how JSON Web Tokens work:

Imagine you’re checking into a hotel, not an API. Tokens are plastic hotel security cards that can be used to enter your room and use hotel facilities, but not anyone else’s room.

When you check out, you hand in your card. This is similar to a write-off.

The structure of the Token

Typically, a JSON Web Token is sent via an HTTP request. Similar to the following:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U
Copy the code

In fact, the Token part is behind the “Authorization: Bearer” and is simply HTTP headers.

Before you conclude that this is incomprehensible gibberish, there are a few things you can easily notice.

First, the Token is made up of three different strings separated by periods. These three parts are Base64 encoded content and correspond to Header, Payload, and Signature respectively.

// Header eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

// Payload eyJzdWIiOiIxMjM0NTY3ODkwIn0

// Signature dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U

Copy the code

Note: Base64 is a method of converting strings to ensure that they are not scrambled during transmission across networks. This is not a form of encryption and can be easily decoded by anyone to see the raw data.

We can decode these strings to better understand the structure of JWT.

Header

The following is the decoded Header portion of the Token. Header is the Token meta information. It doesn’t tell us much to help you build a basic understanding, so we won’t go into any detail about it.

{ 
  "alg": "HS256"."typ": "JWT" 
}
Copy the code

Payload

Payload gets more attention. Payload can contain any data if you want, but if the Token’s purpose is API access authentication, it can contain only the user ID.

{ 
  "userId": "1234567890" 
}
Copy the code

Payload is not secure. Anyone can decode the Token and know exactly what’s in the Payload. Therefore, we typically include an ID rather than sensitive identifying information such as the user’s email.

Even if Payload is all that is needed to identify a user on an API, it does not provide a means of authentication. If it contains everything, someone can easily find your user ID and forge tokens.

So this brings us to the Signature section, which is a key part of authenticating tokens.

The hash algorithm

Before explaining how signatures work, we need to define what a hash algorithm is.

First, it’s a function that converts a string to a new string called a Hash. For example, suppose we want to hash the string “Hello, world”. Here is the output we get using the SHA256 hash algorithm:

4ae7c3b6ac0beff671efa8cf57386151c06e58ca53a78d83f36107316cec125f
Copy the code

The most important property of hashing is that you can’t see the original text of the Hash through the Hash algorithm.

There are many different types of hash algorithms, but SHA256 is commonly used in conjunction with JWT.

In other words, we can’t figure out from the hash value above that the original string is Hello, world. Hashing is too complicated to guess the original string.

JWT signature

Back to the JWT structure, take a look at the third part of an order card, the signature. You actually need to calculate:

HMACSHA256( 
  base64UrlEncode(header) + "." + base64UrlEncode(payload), 
  "secret string"
);
Copy the code

Here’s an explanation of what’s happening here:

First, HMACSHA256 is the name of the hash function and takes two arguments: the string to hash, and “secret.”

Second, the string we hash is the base 64 encoding header, plus the base 64 encoding payload.

Third, secret is an arbitrary string known only to the server.

Q. Why include headers and payloads in signature hashes?

This ensures that the signature is unique to this particular token. *

Q: what is secret?

To answer this question, let’s consider how to forge a token.

As we said earlier, you can’t determine the input to a hash by looking at the output. However, since we know that signatures include headers and payloads because they are public information, you can generate the same hash if you know the hash algorithm (hint: usually specified in the header).

But secrets that only the server knows are * not * public information. Including it in the hash prevents someone from generating their own hash to forge the token. And because hashes obscure the information used to create them, no one can figure out the secret from the hash.

* The process of adding private data to a hash is called * salting and it is almost impossible to crack the token.

# Certification process

So now you have a good idea of how tokens are created. How do you use it to validate your API?

The login

A token is generated when a user logs in, and the token is stored in the database along with the user model.

  • loginController.js *
if (passwordCorrect) { 
  user.token = generateToken(user.id); 
  user.save(); 
}
Copy the code

The token is then attached to the response of the login request as the authorization header.

loginController.js

if (passwordCorrect) { 
  user.token = generateToken(user.id); 
  user.save(); 
  res.headers("authorization", `Bearer ${token}`).send(); 
}
Copy the code

# validate request

The client now has the token, which they can attach to any future request to authenticate the user.

When the server receives a request with an authorization token, the following happens:

1. It decodes the token and extracts the ID from the payload.

2. It uses this ID to look up users in the database.

3. It compares the request token to the token stored in the user model. If they match, the user is authenticated.

authMiddleware.js

const token = req.header.token; 
const payload = decodeToken(token); 
const user = User.findById(payload.id); 
if(user.token = token) {// Pass authentication}else{// Failed to authenticate}Copy the code

Log out

If the user logs out, simply remove the token attached to the user model, and now the token is no longer in effect. The user will need to log in again to generate a new token.

logoutController.js

user.token = null; 
user.save();
Copy the code

conclusion

Therefore, this is the most basic explanation of how to protect the API using JSON Web tokens. I hope you don’t have a headache.

There’s a lot more to it, though, so here’s some extra reading:

  • JWT.io
  • What is a JSON Web token?
  • Know how to use JSON Web token (JWT) for authentication

Original link: learnku.com/laravel/t/4… For discussion, head to the professional Laravel developer forum: learnku.com/Laravel