xaamin/jwt

基于RSA的JSON Web token的PHP实现

v2.0.2 2024-02-14 01:44 UTC

This package is auto-updated.

Last update: 2024-09-14 03:05:39 UTC


README

基于RSA的PHP JSON Web token实现。

支持算法

RSA (Public Key/Private Key pair)

RS256 - RSA using SHA-256 hash algorithm
RS384 - RSA using SHA-384 hash algorithm
RS512 - RSA using SHA-512 hash algorithm

HMAC algorithms : 

HS256 - HMAC using SHA-256 hash algorithm (default)
HS384 - HMAC using SHA-384 hash algorithm
HS512 - HMAC using SHA-512 hash algorithm

安装

使用composer

composer require xaamin/jwt

如何使用RSA的公钥/私钥

src/Config/config.php 中设置配置。生产环境中不要使用这里提供的密钥。

    'algorithm' => 'RS512',
    
    // ... Other stuff here
    
    'keys' => [
        'public' => '../keys/public_key.pem',
        'private' => '../keys/private_key.pem',
        
        'passphrase' => null,
    ],
	$payload = [
			'sub'   => 1,
			'username' => 'xaamin'
	    ];

	// Generate token
	$token = Xaamin\JWT\Facade\Native\JWT::encode($payload);

	// Verify the token
	try{
		$token = Xaamin\JWT\Facade\Native\JWT::decode($token->get());

	    var_dump($token);
	} catch (Exception $e) {
		echo $e->getMessage();
	}

如何使用HMAC

src/Config/config.php 中设置配置

    'algorithm' => 'HS512',

    'secret' => 'some-random-string'
	$payload = [
			'sub'   => 1,
			'username' => 'xaamin'
	    ];

	// Generate token
	$token = Xaamin\JWT\Facade\Native\JWT::encode($payload);

	// Verify the token
	try{
		$token = Xaamin\JWT\Facade\Native\JWT::decode($token->get());

	    var_dump($token);
	} catch (Exception $e) {
		echo $e->getMessage();
	}