Two different approaches for authentication in PHP

If you have worked on some company, you probably had a badge. The badge is a way of authenticate yourself in that environment. But you can be just a visitor, case in which you also should have a badge, just for identification purposes. Note that the badge was given to you by the company, and the company is responsible for verifying if it is valid or not. Note also that the badge should or should not have meaning out of that company, depending on some rules (for instance, a police officer can use the badge to access other buildings besides the police station that emite the badge).

This real-life scenario describes roughly what happens on web applications. A web application is hosted on a web server, which communicates with clients using HTTP protocol and needs a way to identify who is requesting some resource in order to check if that one is authorized or not.

There are some ways of doing this, but on this article we will focus on two of them: session based or token based. Both of them work with the “badge” idea — upon an unidentified request, the server will give something (a cookie or a token) to the client (usually the Browser) and each request the client makes to the server must includes that piece of data so the server can identify who is requesting or if the one making the request is valid or not.

Over the internet we can found some interesting articles about how these authentication methods work and their pros and cons. Here are some of them:

Our goal here is to implement both of them using PHP as back-end with a very simple front-end.

Session based

Let’s start with the simpler one, that can be achieved by using only PHP basic tools.

The first step is to create a HTML response that can only be accessed by authenticated users, so, we need to think of what is the meaning of “being authenticated”. Using that previous real-life example, a company can say that “be authenticated” is equivalent to “I have a file here in my company with your identity code” for instance. Using a session based authentication, being authenticated is equivalent to:

  1. have a valid cookie in the request (you have a badge);
  2. there is a session related to that cookie (the company have a file with your badge identity code);
  3. inside the session has some key/value that tells our application that the user is authenticated (that file says you are authorized).

For this example, let’s say the session must have the key auth with a boolean value true.

PHP has a function called session_start() that makes the “magic” of create or resume a session by setting a cookie in the response or validating a cookie in the request. This function also fill up a superglobal variable called $_SESSION that will be an indexed array.

So, in order to check if a request came from an identified user, we must start the session calling the session_start() function and check if $_SESSION["auth"] === true:

Now, we need a way to make the server add this key into the session variable. We will use the following flow to do that:

Besides showing why I’m a programmer and not a designer, this picture shows how the user interact with the server throughout this authentication method:

  1. The user asks for the login page (it doesn’t matter if it was redirected from the home.php as shown before or if it was just a direct access);
  2. The server start a session and answers with the session cookie and a HTML containing a form;
  3. The user then fills the form and sends a request containing the filled data to the server, alongside the cookie;
  4. The server then checks the validity of the cookie and restore the session from the session storage, checks if the user/password combination is valid and then sets that auth index on the session variable (that is stored back in the session storage); after this, server answers to the user telling that it should proceed to the restricted area;
  5. User then request the restricted page including the cookie, so the server can check if the cookie’s session variable has that auth index and if its true, so the user can access the page content.

Now, let’s check the code:

Now you can put these files in some directory and by running some server check the requests (on the DevTool’s Network tab) by requesting the home.php file:

Token based

The token based approach is slightly more complicated then the previous one, although the flow is very similar. User still needs to receive something from the server, but instead of a Cookie — that will be treated and secured by browser rules — the client gets a token, that should be stored in the client using a JavaScript code. Another difference is that instead of holding information about the token, server must only verify if the token is valid or not. Back on that company example, this is the case where “be authorized” is equivalent to “I can check that your badge is trustful and any information contained that is valid for me”.

Other big difference is that now the front-end programmer needs to be aware of where the token is stored in the client (usually in localStorage) and send it in every request it makes. This implies that a common request built by the browser (for instance, when the user clicks on some <a> element) doesn’t include the token.

This token could be any piece of information, but we must be aware that this information is completely available to the user, so the server will receive an untrusted data that must be verified. The main approach for dealing with this token is Jason Web Tokens (JWT). It is a token that contains some data alongside with a signature that depends on a secret key held by the server.

By knowing this, we can look at the code:

This JavaScript code is one of the main pieces in this application. Note that this file contains the logic of the application, showing or hiding the form and changing the content of the HTML. This is roughly equivalent to some front-end generated by some framework like ReactJS, Vue.js or Svelte, for instance.

The rest of code from now is the back-end built with pure PHP (without using any libraries), limited to HS256 algorithm and without any real-world use besides showing how this works under the hood:

Of course there are some libraries that can deal with JWT for us, written in many different languages (check the jwt.io website), so this functions.php is here just for educational means.

Although more complicated, this is currently how we can deal with authentication and authorization in modern web development using front-end frameworks, since usually we don’t make synchronous requests and all the user interaction is handled by the generated JavaScript code.

Thanks for reading this tutorial, I hope this helps you 😊

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store