Token based authentication in php

Active3 hr before
Viewed126 times

9 Answers


There is no need for server-side sessions - a JWT can contain all the required information about the user, and the information is protected against modification,They are decentralized and portable (you can request a token from a dedicated service, and then use it with multiple backends),JSON Web Tokens (JWTs) have turned into the de-facto standard for stateless authentication of mobile apps, single-page web applications, and machine-to-machine communication. They have mostly superseded the traditional authentication method (server-side sessions) because of some key benefits:,Okta is an API service that allows you to create, edit, and securely store user accounts and user account data, and connect them with one or more applications. Register for a forever-free developer account, and when you’re done, come back to learn more about token authentication in PHP.

composer require firebase / php - jwt
load more v

I'm not understanding how should I authenticate the user using 'Token Based Authentication' in order to access the website's resources.,N.B. : The proposed implementation of 'Token Based Authentication' should be very secure and fast in speed. The security should not be compromised in any way.,1st you should understand what's token based authentication. It could be explained as below.,Hope the above explains your confusion. if you come across any issues implementing token based authentication let me know. I can help you.

To create a token i use this function which takes as parameters, the user's data

define('SECRET_KEY', "fakesecretkey");

function createToken($data) {
   /* Create a part of token using secretKey and other stuff */
   $tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"]; // It can be 'stronger' of course

   /* Encoding token */
   $token = hash('sha256', $tokenGeneric.$data);

   return array('token' => $token, 'userData' => $data);
load more v

For an updated version of this article, see Token Authentication in PHP on the Okta developer blog.,There are great reasons why you would want to use Token Authentication on your next PHP web application. Give the PHP SDK a try for your next project or even integrate it into your existing applications now.,Token based authentication in the PHP SDK removes the need to store information on the server, and allows you to keep tokens secure on the Client. Using Stormpath to generate and verify these tokens for you, access to your web application can be restricted at any time by removing a token from an account.,I am sure every PHP developer has struggled with storing user information on a server to identify the source of a request. Since HTTP is a stateless system, this has been the only way to tell who a user is. Until now! We’ve built Token Authentication directly into the PHP SDK for your applications.

Configuring OAuth Access and Refresh Tokens

The first thing to do is set up your application to allow for Token Management. A new resource has been added to the PHP SDK for managing your application’s OAuth policies. This resource gives you access to the TTLs for application tokens. The TTL values are stored and set as ISO 8601 durations. By default, the application access token is set to 1 hour (PT1H) and the refresh token is set to 60 days (P60D).

ISO 8601

A token is a piece of data that has no meaning or use on its own, but combined with the correct tokenization system, becomes a vital player in securing your application. Token based authentication works by ensuring that each request to a server is accompanied by a signed token which the server verifies for authenticity and only then responds to the request.,We’ve seen how easy it is to implement JWT authentication and secure our API. To conclude, let’s examine use cases where token based authentication is best suited for.,Tokens can be generated from anywhere. Token generation is decoupled from token verification allowing you the option to handle the signing of tokens on a separate server or even through a different company such us Auth0.,Tokens are stateless. The token is self-contained and contains all the information it needs for authentication. This is great for scalability as it frees your server from having to store session state.

A JSON Web Token consists of three parts: Header, Payload and Signature. The header and payload are Base64 encoded, then concatenated by a period, finally the result is algorithmically signed producing a token in the form of The header consists of metadata including the type of token and the hashing algorithm used to sign the token. The payload contains the claims data that the token is encoding. The final result looks like:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZXNzYWdlIjoiSldUIFJ1bGVzISIsImlhdCI6MTQ1OTQ0ODExOSwiZXhwIjoxNDU5NDU0NTE5fQ. - yIVBD5b73C75osbmwwshQNRC7frWUYrqaTjTpza2y4
load more v

That’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.,In this article, you’ll learn what JWTs are and how to use them with PHP to make authenticated user requests.,iss: a string containing the name or identifier of the issuer. Can be a domain name and can be used to discard tokens from other applications.,Now, 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.

Here is a sample JWT:

load more v

JWT tokens are simply encrypted user's information like identifier, username, email and password.,When users are successfully logged in the server, the latter will produce and send a JWT token back to the client.,You should get a Successful login message with a JWT token.,Enter JWTs. A JWT token is simply a JSON object that has information about the user. For example:

   "user": "bob",
   "email": "",
   "access_token": "at145451sd451sd4e5r4",
load more v

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file. , PHP uses the presence of an AuthType directive to determine whether external authentication is in effect. , Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server. , Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

HTTP authentication with PHP

It is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array. Only "Basic" and "Digest" authentication methods are supported. See the header() function for more information.

"Authentication Required"
load more v

If the user is authenticated and the token is valid, we can safely return the restricted data to the frontend via JSON.,On every subsequent request, the server needs to find that session and deserialize it, because user data is stored on the server.,This refers to a JWT, which is passed along via the HTTP header called Authorization, in the string format "Bearer $your_token_here".,JWT stands for JSON Web Token, a common authentication tactic used in modern web apps.

Here is a JWT token example:

load more v

However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.,Finally, in your application's config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests:,Once an access token authenticated request has entered your application, you may still check if the token has a given scope using the tokenCan method on the authenticated App\Models\User instance:,Before your application can issue tokens via the authorization code grant with PKCE, you will need to create a PKCE-enabled client. You may do this using the passport:client Artisan command with the --public option:

To get started, install Passport via the Composer package manager:

composer require laravel / passport
load more v

Other "authentication-token" queries related to "Token based authentication in php"