Howdy, Are you a Laravel dev? Or learning Laravel in deep? Then you must hear the term API, right? API (Application Programming Interface) is a very common thing nowadays in the world of software development. Modern web applications can’t think of it. It's a great medium for data sharing and data authenticity. If you are/want to be a backend developer, learning to integrate API is a must. But how to make them?
As API is an intermediate level concept, I am assuming you are pretty familiar with PHP and Object-Oriented Programming (OOP), Composer and you build/started building pieces of stuff using Laravel. If you’re not familiar with them I highly recommend you to learn them first. For a clear understanding, I broke down this tutorial into two parts. In this part, I will discuss the concept/methodology behind API building and JWT. And in the part 2, I will implement them using JWT and Laravel. If you have a basic concept of them, you can skip this part and move on to the next part.
So what is API?
API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message or check the weather on your phone, you’re using an API. It’s a way of data communication. It lets you share/store/validate data from your application to other applications and vice versa. If you want to share some data publicly/privately to some other application, will you let them modify/access your database? Of course, not, there comes the vital role of API. You can share an endpoint to others where they can store/retrieve data with proper validation and authentication.
Before we dive deep, let's clear some core concepts and processes to authenticate a user using API. So now comes the question, what is authentication? I often see people get confused between authorization and authentication.
Let’s imagine a scenario. You joined/work in an IT company. Whenever you try to enter your office you need to pass the main gate of the building and a guard sitting there asks your identity so that he can be sure that you belong to this office. You somehow(showing you ID card/finger punch) managed to prove your identity and get inside the office building. Now you got a cabin/desk of your own and went there started working. After some time you thought to take a coffee break and went to the canteen/food court of your office. After that, you wanted to look at the server room of the IT department and you got stopped and asked to verify yourself once again as the room is only open for a few people. As you don’t have access there, you returned to your desk and started working again.
Pretty simple scenario right? But wait we were talking about authentication and authorization. Where is that? Well, we will get there soon. So think carefully about the first step in the scenario. You had to prove your identity in order to get inside the office building. Now if you failed to prove your identity would you able to go inside? The answer will be always NO (unless you’re the owner of the building :P ). There’s come the concept of authentication. Authentication means verifying the user whether he has access to the site/application. It’s a root level check or verification for the user. If he doesn’t have access he can’t go further. So the authentication is verifying users at the root level or simply verifying the user’s identity.
Then what is authorization? Remember you went for a coffee break (I mean in the scenario). Did you ask to verify your access there? No, you didn’t have to. Cause the place is open for all(people who are inside the building). But when you tried to make a visit to the server room you were stopped. Because you didn’t have the permission to go there though you are a verified person to the building(even you are a dev person too). Here comes the concept of authorization. Authorization is verifying access to some particular section of the application. That means you might have access through the whole application or your access is restricted to some part of the application though you have logged in the application.
So why we need to know what authentication and authorization are? We were learning to make API, right? Well as I said earlier, API is used to authenticate/authorize users in the application. So we had to know them. And as said in the Laravel documentation:
“When using any tool in the ‘real world’, you feel more confident if you understand how that tool works. Application development is no different. When you understand how your development tools function, you feel more comfortable and confident using them.”
The next thing is understanding the difference between stateful and stateless authentication. Let’s start with the stateful authentication.
Stateful authentication means storing the user’s state/data. In this process after successful authentication, the application generates a random token to send back to the client, then creates a client authenticated session in memory or an internal database. When a client tries to access the application with a given token, the application tries to retrieve session data from session storage, checks if the session is valid or not, then decide whether the client has access to the desired resource or not. These session ids can be stored in a file or database(by maintaining a table), cookies, or using in-memory data structure(such as key-value pair) like Redis, Memcached, etc. It’s a very secure way as the data can not be stolen by a third party during the data transaction and you can retrieve/revoke the users' session/token at any time. But as a coin has two parts, the disadvantages of this process is that you need to store data/token/session ids somewhere else(file/in-memory/database). It can be hard to maintain if the data were not managed properly and need more space. Moreover, horizontal scaling in this process is hard too.
Ok, got the basic idea of stateful authentication. So what is stateless then? Ok, what stateful authentication does? It stores the user's identity somewhere in the server end right? In stateless it doesn’t store the user’s identity on the server-side. Rather than it uses a token or some secret key to authenticate the user. This token is sent by the client during request. Token are sent typically within the header of the request, or as a query parameter. Then the server checks the token structure, matches the combination, and verifies it. This token is generated from the server-side and is stored on the client-side(such as localStorage). Then when any request sent from the client-side the token is passed too. The advantage of such a process is that you don’t have to bother about managing tokens on the server end. The tokens are generated in a nice standard format(JSON, XML) and can hold information about the user along with the expiring time and validity of the token.
Hmm... but again why we need to know that? We are here to learn how to make API right? Yeah, making API but using JWT and Laravel. And the JWT(JSON Web Token) is a part of stateless authentication where the token is served in a well-structured manner and maintained according to some paradigm. Let’s explore together.
What is JWT? As the official documentation says:
“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.”.
That’s a pretty nice definition but allow me to help you understand. JWT or JSON Web Token is a format that helps you to store information as a token in a manner that can be verified/retrieve to others only if the other party knows the combination of it. It’s a large string(token) containing three major parts and separating by dots(.). The three parts are:
Therefore, a JWT typically looks like the following.
Here first red part
is Header, which contains the type and algorithm that will be used to verify the token. This looks something like below when decrypted:
Here, the type is JWT, and the algorithm is used to check the hash is HS256. Here is a list of available hashing algorithms that are supported by JWT.
The middle part is the payload, which typically holds information about the user or when the token was issued, who issued, expiration time, and any custom data you want to pass. But keep in mind that no secret information should be passed as the payload can be extracted.
The third and last part is the secret key that is used to match the combination and verifying that the token has not tampered with. If anybody modifies the payload or the header part, the combination with the secret key will be different. Thus the original token and newly/modified token will mismatch and the token will be marked as blacklisted/invalid. Once the token gets blacklisted you can not use the same token to request further.
Enough with the theory, let’s move on to hands-on implementation. Check out part 2.