georgechem / jwt-auth
用于生成和验证JSON Web Token的简单库
v1.0.1
2021-10-25 14:03 UTC
Requires
- php: >=8.0.0
- firebase/php-jwt: ^5.4
- georgechem/sqlite-db: dev-master
- vlucas/phpdotenv: ^5.3
This package is auto-updated.
Last update: 2024-09-07 18:13:15 UTC
README
使用composer安装
composer require georgechem/jwt-auth
在项目的根目录中创建一个.env文件,如下所示
SERVER_SECRET='your server secret' TOKEN_EXPIRE='5 minutes' // use time according to your needs SERVER_DOMAIN = 'example.com' // server domain HEADER_NAME='jwt-token' //name of header where jwt will be put COOKIE_DOMAIN=localhost // for cookie verification COOKIE_EXPIRE=60 cookie expire time in seconds
要生成令牌:在入口点,通常是index.php,但可以是任何.php文件
要获取令牌,请向入口点发送以下数据的POST请求
$_POST['email'] and $_POST['password'] // data used internally to generate JWT
require __DIR__ . '/vendor/autoload.php'; $jwt = Jwt::getInstance(); // echo json response which can be consumed in javascript $jwt->generate()->jsonResponse();
在入口点验证令牌并验证/授权用户
$jwt = Jwt::getInstance(); /** * Token verified successfully|fail * array[optional] may contain additional options for verifications * like: user role, server name etc... * @Return bool */ $jwt->verify(array());
示例用法
获取新用户或已注册用户的令牌
use Georgechem\JwtAuth\Jwt\Jwt; require __DIR__ . '/vendor/autoload.php'; // coming from traditional form or javascript $_POST['email'] = 'user@email.com'; $_POST['password'] = 'user_password'; $jwt = Jwt::getInstance(); // json response may be consumed by javascript and token can be stored // in local storage $jwt->generate()->jsonResponse();
验证请求的令牌
use Georgechem\JwtAuth\Jwt\Jwt; require __DIR__ . '/vendor/autoload.php'; $jwt = Jwt::getInstance(); $_SERVER['jwt-token'] = 'that.token.should_be_from.header'; // if token is valid (not expired or malformed etc.) if($jwt->verify()){ //can use token data to do additional security checks manually var_dump($jwt->tokenData()); }