How to add jwt token in php?
There was a time when the only way to authenticate yourself with an application was by providing your credentials (usually a username or email address and a password) and a session was then used to maintain user state until the user logged out. A little while later, we started using authentication APIs. And in yet more recent times, JWTs, or JSON Web Tokens, have been increasingly used as another way to authenticate requests to a server. Show
In this article, you’ll learn what JWTs are and how to use them with PHP to make authenticated user requests. JWTs versus SessionsBut first, why are sessions not such a good thing? Well, there are three key reasons:
JWTNow, let’s start learning about JWTs. The JSON Web Token specification (RFC 7519) was first published on December 28, 2010, and was most recently updated in May 2015. JWTs have many advantages over API keys, including:
What Does a JWT Look Like?Here is a sample JWT:
At first glance, it appears that the string is just random groups of characters concatenated with a period or dot character. As such, it may not seem very different from an API key. However, if you look more closely, there are three separate strings. The first string is the JWT header. It’s a Base64, URL-encoded JSON string. It specifies which cryptographic algorithm was used to generate the signature, and the token’s type, which is always set to A symmetric algorithm uses a single key to both create and verify the token. The key is shared between the creator of the JWT and the consumer of it. It’s essential that you make sure only the creator and consumer knows the secret. Otherwise, anyone can create a valid token. An asymmetric algorithm uses a private key to sign the token and a public key to verify it. These algorithms should be used when a shared secret is impractical or other parties only need to verify the integrity of the token. The JWT’s PayloadThe second string is the JWT’s payload. It’s also a Base64, URL-encoded JSON string. It contains some standard fields, which are referred to as “claims”. There are three types of claims: registered, public, and private. Registered claims are predefined. You can find a list of them in the JWT’s RFC. Here are some commonly used ones:
Public claims can be defined as you see fit. However, they can’t be the same as registered claims, or claims of already existing public claims. You can create private claims at will. They’re only for use between two parties: a producer and a consumer. The JWT’s SignatureThe JWT’s signature is a cryptographic mechanism designed to secure the JWT’s data with a digital signature unique to the contents of the token. The signature ensures the JWT’s integrity so that consumers can verify it hasn’t been tampered with by a malicious actor. The JWT’s signature is a combination of three things:
These three are digitally signed (not encrypted) using the algorithm specified in the JWT’s header. If we decode the example above, we’ll have the following JSON strings: The JWT’s Header
The JWT’s Data
Try out jwt.io for yourself, where you can play around with encoding and decoding your own JWTs. Let’s Use JWTs in a PHP-based ApplicationNow that you’ve learned what JWTs are, it’s now time to learn how to use them in a PHP app. Before we dive in, feel free to clone the code for this article, or follow along and create it as we go. There are many ways that you can approach integrating JWTs, but here’s how we’re going to do it. All requests to the application, except for the login and logout page, need to be authenticated via a JWT. If a user makes a request without a JWT, they’ll be redirected to the login page. After a user fills out and submits the login form, the form will be submitted via JavaScript to the login endpoint, If they are, it will generate a JWT and send it back to the client. When the client receives a JWT, it will store it and use it with every future request to the application. For a simplistic scenario, there’ll only be one
resource the user can request — a PHP file aptly named There’s couple of ways to use JWTs when making requests. In our application, the JWT will be sent in the Bearer authorization header. If you’re not familiar with Bearer Authorization, it’s a form of HTTP authentication, where a token (such as a JWT) is sent in a request header. The server can inspect the token and determine if access should be given to the “bearer” of the token. Here’s an example of the header:
For each request received by our application, PHP will attempt to extract the token from the Bearer header. If it’s present, it’s then validated. If it’s valid, the user will see the normal response for that request. If the JWT is invalid, however, the user won’t be allowed to access the resource. Please note that JWT was not designed to substitute session cookies. PrerequisitesTo begin with, we need to have PHP and Composer installed on our systems. In the project’s root, run The Login FormWith the
library installed, let’s step through the login code in
After receiving the form submission, the credentials are validated against a database, or some other data store. For the purposes of this example, we’ll assume that they’re valid, and set
Next, we initialize a set of variables to be used for generating the JWT. Please bear in mind that since a JWT can be inspected client-side, do not include any sensitive information in it. Another thing worth pointing out, again, is that Never disclose it or store it under version control!
With the payload data ready to go, we next use php-jwt’s static The method:
It takes three parameters:
By calling
Consuming the JWTNow that the client has the token, you can store it using JavaScript or whichever mechanism you prefer. Here’s an example of how to do so using vanilla JavaScript. In
Using the JWTWhen clicking on the “Get current timestamp” button, a GET request is made to
When we click the button, a request similar to the following is made:
Assuming that the JWT is valid, we’d see the resource, after which the response is written to the console. Validating the JWTFinally, let’s look at how we can validate the token in PHP. As always, we’d include Composer’s autoloader. We could then, optionally, check if the correct request method’s been used. I’ve skipped over the code to do that, to continue focusing on the JWT-specific code:
Then, the code would attempt to extract the token from the Bearer header. I’ve done so using preg_match. If you’re not familiar with the function, it performs a regular expression match on a string The regular expression that I’ve used here will attempt to extract the token from the Bearer header, and dump everything else. If it’s not found, an HTTP 400 Bad Request is returned:
Note that, by default, Apache will not
pass the
I fully appreciate the logic of this decision. However, to avoid a lot of confusion, add the following to your Apache configuration. Then the code will function as expected. If you’re using NGINX, the code should function as expected:
Next, we attempt to extract the matched JWT, which would be in the second element of the
If we get to this point, a JWT was extracted, so we move to the decoding and validation stage. To do
that, we need our secret key again, which would be pulled from the environment or the application’s configuration. We then use php-jwt’s static If it’s able to be successfully decoded, we then attempt to validate it. The example I have here is quite simplistic, as it only uses the issuer, not before and expiry timestamps. In a real application, you’d likely use a number of other claims as well.
If the token isn’t valid because, for example, the token has expired, the user will be sent an HTTP 401 Unauthorized header, and the script will exit. If the process to decode the JWT fails, it could be that:
As you can see, JWT has a nice set of controls that will mark it as invalid, without the need to manually revoke it or check it against a list of valid tokens. If the decode and validation process succeeds, the user will be allowed to make the request, and will be sent the appropriate response. In ConclusionThat’s a quick introduction to JSON Web Tokens, or JWTs, and how to use them in PHP-based applications. From here on, you can try to implement JWTs in your next API, maybe trying some other signing algorithms that use asymmetric keys like RS256, or integrating it in an existing OAUTH2 authentication server to be the API key. If you have any comments or questions, feel free to get in touch on Twitter. How use JWT token for authentication in PHP?Once you've installed composer, run the tool from your project folder. Composer will assist you in installing Firebase PHP-JWT, a third-party library for working with JWTs and Apache. Once the library is installed, you'll need to set up a login code in authenticate. php .
Where do I put the JWT token?To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.
How use JWT token in Core PHP?Start PHP-JWT for beginners.
– In the payload section, there is variable “exp,” “exp” variable is used to record when token expires. “exp” is the date converted to time. If using PHP, you can use the time() function. – Do not forget to use the try-catch function to encode and decode JWT token.
How can I get authorization token in PHP?To send a GET request with a Bearer Token authorization header using PHP, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
|