Home Backend Development PHP Tutorial PHP development: How to use JWT for authentication and authorization

PHP development: How to use JWT for authentication and authorization

Jun 14, 2023 pm 04:14 PM
jwt Authentication Authorize

In modern web application development, security has become an integral part. Authentication and authorization are crucial in this regard, as they ensure that only authorized users can access protected resources. There are many authentication and authorization mechanisms available, of which JWT (JSON Web Token) is a particularly popular mechanism because it is simple, flexible, scalable and secure. In this article, we will explore how to use PHP and JWT for authentication and authorization.

Part One: JWT Basics

JSON Web Token (JWT) is an open standard for securely transmitting claims and authentication information over the web. It consists of three parts: header, payload and signature.

The header contains algorithm and token type information. An example of it might look like this:

{
  "alg": "HS256",
  "typ": "JWT"
}
Copy after login

The payload contains the information that needs to be transmitted. For example, username, role and other information about the user. An example of a payload might look like this:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}
Copy after login

A signature is an encrypted string containing the key used to verify that the JWT is valid. An example of a signature might look like this:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(claims),
  secret)
Copy after login

Part Two: Implementing JWT using PHP

In order to use JWT for authentication and authorization, we need a PHP class to generate and validate the JWT. Let’s look at the implementation of a simple PHP JWT class.

<?php

class JWT {
  private $header;
  private $payload;
  private $secret;

  public function __construct($header, $payload, $secret) {
    $this->header = $header;
    $this->payload = $payload;
    $this->secret = $secret;
  }

  public function encode() {
    $header = $this->base64UrlEncode(json_encode($this->header));
    $payload = $this->base64UrlEncode(json_encode($this->payload));
    $signature = $this->base64UrlEncode(hash_hmac('sha256', $header . '.' . $payload, $this->secret, true));
    return $header . '.' . $payload . '.' . $signature;
  }

  public function decode($jwt) {
    $parts = explode('.', $jwt);
    $header = json_decode($this->base64UrlDecode($parts[0]), true);
    $payload = json_decode($this->base64UrlDecode($parts[1]), true);
    $signature = $this->base64UrlDecode($parts[2]);
    $result = hash_hmac('sha256', $parts[0] . '.' . $parts[1], $this->secret, true);
    if (hash_equals($result, $signature)) {
      return $payload;
    } else {
      return null;
    }
  }

  private function base64UrlEncode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
  }

  private function base64UrlDecode($data) {
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
  }
}
Copy after login

In this PHP class, $header, $payload and $secret store the JWT header, payload and secret information. The encode() method uses header, payload, and secret to generate a JWT string. decode() Method uses the given JWT string and key to get the payload information. The

base64UrlEncode() and base64UrlDecode() methods are used to encode and decode the JWT header and payload.

Part Three: Using JWT for Authentication and Authorization

Now, we have understood the basics of JWT and have a PHP JWT class for generating and validating JWT. So, how do we use JWT for authentication and authorization?

First, when a user logs in, a token can be sent using JWT to authenticate their identity. The server will generate a JWT with the username and password payload and send it to the client. The client will send this token as the Authorization header of the Bearer authentication scheme on every request. The server will extract the JWT from the header and verify its validity if necessary.

The following is a sample JWT implementation for authentication and authorization:

<?php

// 使用 JWT 登录
function login($username, $password) {
  // 检查用户名和密码是否正确
  $is_valid = validate_user_credentials($username, $password);
  if (!$is_valid) {
    return null;
  }

  // 生成 JWT
  $header = array('alg' => 'HS256', 'typ' => 'JWT');
  $payload = array('sub' => $username);
  $jwt = new JWT($header, $payload, $GLOBALS['secret']);
  $token = $jwt->encode();

  // 返回 JWT
  return $token;
}

// 验证 JWT
function validate_token($jwt) {
  $jwt = new JWT($header, $payload, $GLOBALS['secret']);
  $payload = $jwt->decode($jwt);
  if ($payload == null) {
    return false;
  }

  // 验证成功
  return true;
}

// 保护资源
function protect_resource() {
  // 检查 JWT 是否有效
  $jwt = get_authorization_header();
  if (!validate_token($jwt)) {
    http_response_code(401);
    exit();
  }

  // 资源保护
  // ...
}

// 从标头获取 JWT
function get_authorization_header() {
  $headers = getallheaders();
  if (isset($headers['Authorization'])) {
    return $headers['Authorization'];
  }
  return null;
}

// 检查用户名和密码是否正确
function validate_user_credentials($username, $password) {
  // 验证用户名和密码
  // ...
  return true;
}

// 密钥
$GLOBALS['secret'] = "my-secret";

// 登录并获取 JWT
$token = login("username", "password");

// 将 JWT 添加到标头
$headers = array('Authorization: Bearer ' . $token);

// 保护资源
protect_resource($headers);
Copy after login

In this example, the login() method uses the JWT class Create a JWT and return it for consumption by the client. validate_token() method can verify the validity of JWT. If the JWT is invalid, false will be returned.

get_authorization_header() Method extracts the JWT from the request header. protect_resource() The method is used to protect web resources. If the JWT is invalid, this function will raise a 401 error.

Finally, a secret is defined in the global scope, $GLOBALS ['secret'] , which should be a long string. Note that this password is a secret password and should not be included in your code base. Typically, this key is stored in an environment variable and managed by the operating system running the web server.

Conclusion

JWT is a very simple, flexible, scalable and secure mechanism that can be used for authentication and authorization in web applications. In this article, we have looked at the basics of JWT and seen a sample PHP class for generating and validating JWT. We also saw how JWT can be used for authentication and authorization. Now you can try JWT in your web applications to ensure your apps are more secure.

The above is the detailed content of PHP development: How to use JWT for authentication and authorization. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to upgrade win10 enterprise version 2016 long-term service version to professional version How to upgrade win10 enterprise version 2016 long-term service version to professional version Jan 03, 2024 pm 11:26 PM

When we no longer want to continue using the current Win10 Enterprise Edition 2016 Long-Term Service Edition, we can choose to switch to the Professional Edition. The method is also very simple. We only need to change some contents and install the system image. How to change win10 enterprise version 2016 long-term service version to professional version 1. Press win+R, and then enter "regedit" 2. Paste the following path directly in the address bar above: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion3 , then find the EditionID and replace the content with "professional" to confirm

How to use JWT and JWE for API authentication and encryption in PHP How to use JWT and JWE for API authentication and encryption in PHP Jun 17, 2023 pm 02:42 PM

With the development of the Internet, more and more websites and applications need to provide API interfaces for data interaction. In this case, API authentication and encryption become very important issues. As a popular authentication and encryption mechanism, JWT and JWE are increasingly used in PHP. Well, this article will explain how to use JWT and JWE for API authentication and encryption in PHP. Basic concepts of JWT JWT stands for JSONWe

How to use ThinkPHP6 for JWT authentication? How to use ThinkPHP6 for JWT authentication? Jun 12, 2023 pm 12:18 PM

JWT (JSONWebToken) is a lightweight authentication and authorization mechanism that uses JSON objects as security tokens to securely transmit user identity information between multiple systems. ThinkPHP6 is an efficient and flexible MVC framework based on PHP language. It provides many useful tools and functions, including JWT authentication mechanism. In this article, we will introduce how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications

OAuth in PHP: Create a JWT authorization server OAuth in PHP: Create a JWT authorization server Jul 28, 2023 pm 05:27 PM

OAuth in PHP: Creating a JWT authorization server With the rise of mobile applications and the trend of separation of front-end and back-end, OAuth has become an indispensable part of modern web applications. OAuth is an authorization protocol that protects users' resources from unauthorized access by providing standardized processes and mechanisms. In this article, we will learn how to create a JWT (JSONWebTokens) based OAuth authorization server using PHP. JWT is a type of

Analysis of secure JWT token generation and verification technology in PHP Analysis of secure JWT token generation and verification technology in PHP Jul 01, 2023 pm 06:06 PM

Analysis of Secure JWT Token Generation and Verification Technology in PHP With the development of network applications, user authentication and authorization are becoming more and more important. JsonWebToken (JWT) is an open standard (RFC7519) for securely transmitting information in web applications. In PHP development, it has become a common practice to use JWT tokens for user authentication and authorization. This article will introduce secure JWT token generation and verification technology in PHP. 1. Basic knowledge of JWT in understanding how to generate and

A complete guide to implementing login authentication in Vue.js (API, JWT, axios) A complete guide to implementing login authentication in Vue.js (API, JWT, axios) Jun 09, 2023 pm 04:04 PM

Vue.js is a popular JavaScript framework for building dynamic web applications. Implementing user login authentication is one of the necessary parts of developing web applications. This article will introduce a complete guide to implementing login verification using Vue.js, API, JWT and axios. Creating a Vue.js Application First, we need to create a new Vue.js application. We can create a Vue.js application using VueCLI or manually. Install axiosax

How to use Flask-Security to implement user authentication and authorization How to use Flask-Security to implement user authentication and authorization Aug 04, 2023 pm 02:40 PM

How to use Flask-Security to implement user authentication and authorization Introduction: In modern web applications, user authentication and authorization are essential functions. To simplify this process, Flask-Security is a very useful extension that provides a series of tools and functions to make user authentication and authorization simple and convenient. This article will introduce how to use Flask-Security to implement user authentication and authorization. 1. Install the Flask-Security extension: at the beginning

UniApp implements detailed analysis of user login and authorization UniApp implements detailed analysis of user login and authorization Jul 05, 2023 pm 11:54 PM

UniApp implements detailed analysis of user login and authorization. In modern mobile application development, user login and authorization are essential functions. As a cross-platform development framework, UniApp provides a convenient way to implement user login and authorization. This article will explore the details of user login and authorization in UniApp, and attach corresponding code examples. 1. Implementation of user login function Create login page User login function usually requires a login page, which contains a form for users to enter their account number and password and a login button

See all articles