JSON Web Token (JWT) for webman plugin

Overview

JSON Web Token (JWT) for webman plugin

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。

JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。

认证&授权流程

image

签名流程

  1. 用户使用用户名和口令到认证服务器上请求认证。
  2. 认证服务器验证用户名和口令后,以服务器端生成JWT Token,这个token的生成过程如下:
    • 认证服务器还会生成一个 Secret Key(密钥)
    • 对JWT Header和JWT Payload分别求Base64。在Payload可能包括了用户的抽象ID和的过期时间。
    • 用密钥对JWT签名 HMAC-SHA256(SecertKey, Base64UrlEncode(JWT-Header)+'.'+Base64UrlEncode(JWT-Payload))
  3. 然后把 base64(header).base64(payload).signature 作为 JWT token返回客户端。
  4. 客户端使用JWT Token向应用服务器发送相关的请求。这个JWT Token就像一个临时用户权证一样。

安装

composer require tinywan/jwt

使用

生成令牌

use Tinywan\Jwt\JwtToken;

$user = [
    'uid'  => 2022,
    'name'  => 'Tinywan',
    'email' => 'Tinywan@163.com'
];
$token = JwtToken::generateToken($user);
var_dump(json_encode($token));

输出(json格式)

{
    "token_type": "Bearer",
    "expires_in": 36000,
    "access_token": "eyJ0eXAiOiJAUR-Gqtnk9LUPO8IDrLK7tjCwQZ7CI...",
    "refresh_token": "eyJ0eXAiOiJIEGkKprvcccccQvsTJaOyNy8yweZc..."
}

响应参数

参数 类型 描述 示例值
token_type string Token 类型 Bearer
expires_in int 凭证有效时间,单位:秒 36000
access_token string 访问凭证 XXXXXXXXXXXXXXXXXXXX
refresh_token string 刷新凭证(访问凭证过期使用 ) XXXXXXXXXXXXXXXXXXX

支持函数列表

1、获取当前uid

$uid = Tinywan\Jwt\JwtToken::getCurrentId();

2、获取所有字段

$email = Tinywan\Jwt\JwtToken::getExtend();

3、获取自定义字段

$email = Tinywan\Jwt\JwtToken::getExtendVal('email');

4、刷新令牌(通过刷新令牌获取访问令牌)

$refreshToken = Tinywan\Jwt\JwtToken::refreshToken();

5、获令牌有效期剩余时长

$exp = Tinywan\Jwt\JwtToken::getTokenExp();

6、单设备登录。默认是关闭,开启请修改配置文件config/plugin/tinywan/jwt

'is_single_device' => true,

7、获取当前用户信息(模型)

$user = Tinywan\Jwt\JwtToken::getUser();

该配置项目'user_model'为一个匿名函数,默认返回空数组,可以根据自己项目ORM定制化自己的返回模型

ThinkORM 配置

'user_model' => function($uid) {
// 返回一个数组
return \think\facade\Db::table('resty_user')
	->field('id,username,create_time')
	->where('id',$uid)
	->find();
}

LaravelORM 配置

'user_model' => function($uid) {
// 返回一个对象
return \support\Db::table('resty_user')
	->where('id', $uid)
	->select('id','email','mobile','create_time')
	->first();
}

签名算法

JWT 最常见的几种签名算法(JWA):HS256(HMAC-SHA256)RS256(RSA-SHA256) 还有 ES256(ECDSA-SHA256)

JWT 算法列表如下

+--------------+-------------------------------+--------------------+
   | "alg" Param  | Digital Signature or MAC      | Implementation     |
   | Value        | Algorithm                     | Requirements       |
   +--------------+-------------------------------+--------------------+
   | HS256        | HMAC using SHA-256            | Required           |
   | HS384        | HMAC using SHA-384            | Optional           |
   | HS512        | HMAC using SHA-512            | Optional           |
   | RS256        | RSASSA-PKCS1-v1_5 using       | Recommended        |
   |              | SHA-256                       |                    |
   | RS384        | RSASSA-PKCS1-v1_5 using       | Optional           |
   |              | SHA-384                       |                    |
   | RS512        | RSASSA-PKCS1-v1_5 using       | Optional           |
   |              | SHA-512                       |                    |
   | ES256        | ECDSA using P-256 and SHA-256 | Recommended+       |
   | ES384        | ECDSA using P-384 and SHA-384 | Optional           |
   | ES512        | ECDSA using P-521 and SHA-512 | Optional           |
   | PS256        | RSASSA-PSS using SHA-256 and  | Optional           |
   |              | MGF1 with SHA-256             |                    |
   | PS384        | RSASSA-PSS using SHA-384 and  | Optional           |
   |              | MGF1 with SHA-384             |                    |
   | PS512        | RSASSA-PSS using SHA-512 and  | Optional           |
   |              | MGF1 with SHA-512             |                    |
   | none         | No digital signature or MAC   | Optional           |
   |              | performed                     |                    |
   +--------------+-------------------------------+--------------------+

   The use of "+" in the Implementation Requirements column indicates
   that the requirement strength is likely to be increased in a future
   version of the specification.

可以看到被标记为 Recommended 的只有 RS256 和 ES256。

对称加密算法

插件安装默认使用HS256 对称加密算法。

HS256 使用同一个「secret_key」进行签名与验证。一旦 secret_key 泄漏,就毫无安全性可言了。因此 HS256 只适合集中式认证,签名和验证都必须由可信方进行。

非对称加密算法

RS256 系列是使用 RSA 私钥进行签名,使用 RSA 公钥进行验证。

公钥即使泄漏也毫无影响,只要确保私钥安全就行。RS256 可以将验证委托给其他应用,只要将公钥给他们就行。

以下为RS系列算法生成命令,仅供参考

RS512

ssh-keygen -t rsa -b 4096 -E SHA512 -m PEM -P "" -f RS512.key
openssl rsa -in RS512.key -pubout -outform PEM -out RS512.key.pub

RS512

ssh-keygen -t rsa -b 4096 -E SHA354 -m PEM -P "" -f RS384.key
openssl rsa -in RS384.key -pubout -outform PEM -out RS384.key.pub

RS256

ssh-keygen -t rsa -b 4096 -E SHA256 -m PEM -P "" -f RS256.key
openssl rsa -in RS256.key -pubout -outform PEM -out RS256.key.pub

🚀 视频地址

不懂的同学可以了解一下视频,会有详细的说明哦

安全性

https://www.w3cschool.cn/fastapi/fastapi-cmia3lcw.html

概念

有许多方法可以处理安全性、身份认证和授权等问题。而且这通常是一个复杂而「困难」的话题。在许多框架和系统中,仅处理安全性和身份认证就会花费大量的精力和代码(在许多情况下,可能占编写的所有代码的 50% 或更多)。

Jwt 可帮助你以标准的方式轻松、快速地处理安全性,而无需研究和学习所有的安全规范。

场景

假设您在某个域中拥有后端API。并且您在另一个域或同一域的不同路径(或移动应用程序)中有一个前端。并且您希望有一种方法让前端使用用户名和密码与后端进行身份验证。我们可以使用OAuth2通过JWT来构建它。

认证流程

  • 用户在前端输入username和password,然后点击Enter。
  • 前端(在用户的浏览器中运行)发送一个username和password我们的API在一个特定的URL(以申报tokenUrl="token")。
  • API 检查username和password,并用“令牌”响应(我们还没有实现任何这些)。“令牌”只是一个包含一些内容的字符串,我们稍后可以使用它来验证此用户。通常,令牌设置为在一段时间后过期。因此,用户稍后将不得不再次登录。如果代币被盗,风险就小了。它不像一个永久有效的密钥(在大多数情况下)。 前端将该令牌临时存储在某处。
  • 用户单击前端以转到前端 Web 应用程序的另一部分。
  • 前端需要从 API 获取更多数据。但它需要对该特定端点进行身份验证。因此,为了使用我们的 API 进行身份验证,它会发送Authorization一个值为Bearer加上令牌的标头。如果令牌包含foobar,则Authorization标头的内容将为:Bearer foobar。
You might also like...
Probando JWT en Laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Rest API - JWT - Symfony5

Symfony5 JWT - REST API Example Symfony5 JWT - REST API Example Built With PHP Symfony 5 PostgreSQL Getting Started This is an example of how you may

PSR-7 and PSR-15 JWT Authentication Middleware

PSR-7 and PSR-15 JWT Authentication Middleware This middleware implements JSON Web Token Authentication. It was originally developed for Slim but can

PHP package for JWT

PHP-JWT A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519. Installation Use composer to manage your dependenc

Laravel JWT-Authentication API starter kit for rapid backend prototyping.

Laravel JWT API A Laravel JWT API starter kit. Features Laravel 8 Login, register, email verification and password reset Authentication with JWT Socia

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Single file PHP that can serve as a JWT based authentication provider to the PHP-CRUD-API project

Single file PHP that can serve as a JWT based authentication provider to the PHP-CRUD-API project

Sistema de Administrativo - Cliente e Vendedor - Autenticação JWT e Relacionamentos  BD
Sistema de Administrativo - Cliente e Vendedor - Autenticação JWT e Relacionamentos BD

Hi there, My name is ATTILA SAMUELL TABORY, I love technology 👋 Sistema Administrativo Laravel e Vue JS - JWT e Relacionamentos BD Sistema Administra

Aplicação criada com Slim Framework com objetivo de criar autenticação com JWT e aprender sobre o framework Slim

Slim JWT App Essa aplicação tem como foco o aprendizado do Framework Slim e também a utilização de JWT. Como rodar a Aplicação A aplicação está config

Comments
  • refreshtoken过期的问题

    refreshtoken过期的问题

    按照目前这种情况,假如token有效期两小时,refreshtoken有效期7天。token过期了,可以凭refreshtoken获取新token,但是refreshtoken一直是7天有效期的话,就会出现,当refreshtoken过期了的时候,就需要重新登录了,这种场景下,就可能会出现用户正在正常使用的过程中,突然需要重新登录了

    question 
    opened by woann 11
Releases(v1.6.0)
  • v1.6.0(Dec 17, 2022)

  • v1.5.2(Dec 9, 2022)

  • v1.5.0(Oct 8, 2022)

    Full Changelog: https://github.com/Tinywan/webman-jwt/compare/v1.4.0...v1.5.0

    8、令牌清理

    $res = Tinywan\Jwt\JwtToken::clear();
    

    只有配置项 is_single_devicetrue 才会生效

    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Oct 1, 2022)

    Full Changelog: https://github.com/Tinywan/webman-jwt/compare/v1.3.1...v1.4.0

    • fix:is_single_device为true。新生成token后,原有的token自动失效
    Source code(tar.gz)
    Source code(zip)
  • v1.3.1(Aug 3, 2022)

    Bug修复

    • 开启单点登录后,在access_token过期后,用refresh_token请求刷新出现问题。https://www.workerman.net/q/8953

    Full Changelog: https://github.com/Tinywan/webman-jwt/compare/v1.3.0...v1.3.1

    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Jun 28, 2022)

    新增功能

    • 刷新token的时候除了返回access_token之外还返回refresh_token

    用户诉求

    在用户登录的时候,返回access_token和refrsh_token,access_token的过期时间我设置1天,refrsh_token的过期时间我设置7天,只要用户在使用app的时候,access_token一过期,就可以用refrsh_token刷新access_token,那我想说的是,如果用户在使用app的时候,正好在refrsh_token快过期的时候使用app,第一,access_token过期,去找refrsh_token,而这时候refrsh_token也正好过期了,那这个用户的app就直接被弹出来说你要登录,一个用户用app好好的,怎么可能被强制弹出来说要登录呢,我希望这个被强制弹出来登录的情况不存在,也就是之前我所说的,在用refrsh_token刷新access_token的时候,除了返回access_token的同时,还希望返回refrsh_token,那么无论这两个token的过期时间设多久,都不会出现被强制退出来登录的情况。更多:https://www.workerman.net/q/8064#reply_12566

    Full Changelog: https://github.com/Tinywan/webman-jwt/compare/v1.2.6...v1.3.0

    Source code(tar.gz)
    Source code(zip)
  • v1.2.6(Jun 28, 2022)

  • v1.2.5(May 5, 2022)

    • 1、移除配置项:令牌签发时间 iat
    • 2、刷新令牌获取访问令牌令牌签发时间存在bug问题,感谢 @woann 反馈

    Full Changelog: https://github.com/Tinywan/webman-jwt/compare/v1.2.4...v1.2.5

    Source code(tar.gz)
    Source code(zip)
  • v1.2.4(Apr 20, 2022)

    Full Changelog: https://github.com/Tinywan/webman-jwt/compare/v1.2.3...v1.2.4

    支持获取当前用户信息(模型),支持LaravelORM和ThinkORM

    $user = Tinywan\Jwt\JwtToken::getUser();
    

    该配置项目'user_model'为一个匿名函数,默认返回空数组,可以根据自己项目ORM定制化自己的返回模型

    ThinkORM 配置

    'user_model' => function($uid) {
    // 返回一个数组
    return \think\facade\Db::table('resty_user')
      ->field('id,username,create_time')
      ->where('id',$uid)
      ->find();
      }
    

    LaravelORM 配置

    'user_model' => function($uid) {
    // 返回一个对象
    return \support\Db::table('resty_user')
      ->where('id', $uid)
      ->select('id','email','mobile','create_time')
      ->first();
    }
    
    Source code(tar.gz)
    Source code(zip)
  • v1.2.3(Apr 17, 2022)

  • v1.2.2(Mar 29, 2022)

  • v1.2.1(Mar 25, 2022)

  • v1.2.0(Mar 24, 2022)

    • firebase/php-jwt update 6.1
    • This version is compatible with PHP >= 7.1
    • Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0
    • Add parameter typing and return types
    • Better PHPDoc / IDE support
    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Mar 24, 2022)

  • v1.1.1(Mar 23, 2022)

  • v1.1.0(Mar 18, 2022)

  • v1.0.1(Mar 18, 2022)

    • 配置项增加:时钟偏差冗余时间,单位秒。建议这个余地应该不大于几分钟
    • JWT::decode($payload, $keys) 返回类型是 stdClass对象,转换为数组返回
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Feb 24, 2022)

  • v0.0.2(Feb 21, 2022)

  • v0.0.1(Feb 21, 2022)

Owner
ShaoBo Wan(無尘)
You insist, believe in yourself, Yes 👍
 ShaoBo Wan(無尘)
🔐 JSON Web Token Authentication for Laravel & Lumen

Documentation Documentation for 1.* here For version 0.5.* See the WIKI for documentation. Supported by Auth0 If you want to easily add secure authent

Sean Tymon 10.7k Dec 31, 2022
Un proyecto que crea una API de usuarios para registro, login y luego acceder a su información mediante autenticación con JSON Web Token

JSON WEB TOKEN CON LARAVEL 8 Prueba de autenticación de usuarios con una API creada en Laravel 8 Simple, fast routing engine. License The Laravel fram

Yesser Miranda 2 Oct 10, 2021
🔐 JSON Web Token Authentication for Laravel & Lumen

Credits This repository it a fork from original tymonsdesigns/jwt-auth, we decided to fork and work independent because the original one was not being

null 490 Dec 27, 2022
Implements a Refresh Token system over Json Web Tokens in Symfony

JWTRefreshTokenBundle The purpose of this bundle is manage refresh tokens with JWT (Json Web Tokens) in an easy way. This bundles uses LexikJWTAuthent

Marcos Gómez Vilches 568 Dec 28, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC for webman plugin

An authorization library that supports access control models like ACL, RBAC, ABAC for webman plugin

PHP-Casbin 18 Dec 30, 2022
Minimalistic token-based authorization for Laravel API endpoints.

Bearer Minimalistic token-based authorization for Laravel API endpoints. Installation You can install the package via Composer: composer require ryang

Ryan Chandler 74 Jun 17, 2022
JWT auth for Laravel and Lumen

JWT Artisan Token auth for Laravel and Lumen web artisans JWT is a great solution for authenticating API requests between various services. This packa

⑅ Generation Tux ⑅ 141 Dec 21, 2022
Laravel Auth guard for FusionAuth JWT

Laravel FusionAuth JWT Implement an Auth guard for FusionAuth JWTs in Laravel. It ships with also a middleware to check against the user role. Install

Theraloss 7 Feb 21, 2022
Security Defense for Firebase's PHP-JWT Library

PHP-JWT-Guard Protect your code from being impacted by issue 351 in firebase/php-jwt. Installation First, install this library with Composer: composer

Paragon Initiative Enterprises 8 Nov 27, 2022
Simple JWT Auth support for Laravel PHP Framework

Laravel JWT Simple JWT Auth for Laravel PHP Framework using Firebase JWT under the hood. Installation Standard Composer package installation: composer

Ricardo Čerljenko 34 Nov 21, 2022