ktnw / jwt_support
jwt component for laravel
Requires
- tymon/jwt-auth: ^1.0
This package is auto-updated.
Last update: 2025-03-24 12:09:21 UTC
README
介绍
jwt component for laravel
功能说明
集成jwt
使用说明
step1. 引入
composer require ktnw/jwt_support
step2. 发布
php artisan vendor:publish --provider="Ktnw\JwtSupport\Providers\JwtSupportServiceProvider"
step3. 修改中间件的namespace
php artisan support:jwt
step4. 生成jwt的加密秘钥
php artisan jwt:secret
step5: 修改配置文件
App\Http\Kernel的$routeMiddleware中添加:
'jwt_refresh' => \App\Http\Middleware\JwtRefresh::class
修改后,即可在路由中使用该中间件。
app\config目录的auth.php修改:
guards->api->driver改为: 由原来的token改为jwt.
示例如下:'guards' => [ 'api' => [ 'driver' => 'jwt', // 原为token 现改为jwt 'provider' => 'users', 'hash' => false, ] ],
providers->users->model改为: 自己的用户ORM类;
示例如下:'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\SysUser::class, // 这里根据业务需求,改为用户ORM类; ], ],
step6.配置用户ORM类
namespace App\Models;
use App\Traits\BaseModelTrait; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as AuthUser; use Tymon\JWTAuth\Contracts\JWTSubject;
/**
- Class User. *
@package namespace App\Models; */ class User extends AuthUser implements JWTSubject { use Notifiable; protected $fillable = []; protected $hidden = []; protected $table = 'users'; public $timestamps = FALSE;
/**
- Get the identifier that will be stored in the subject claim of the JWT. *
- @return mixed */ public function getJWTIdentifier() { return $this->getKey(); }
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
step7. 建议把jwt.php配置文件中的JWT_SECRET、JWT_TTL、JWT_REFRESH_TTL等配置信息放到.env的配置文件中。
####jwt生成TOKEN示例
注:
$authUser为step6中配置的用户类的实例。
use Tymon\JWTAuth\Facades\JWTAuth;
// 第一种生成token方式 $jwtToken = JWTAuth::fromUser($authUser);
// 第二种生成token方式 $jwtToken = auth('api')->login($userInfo);