安装 JWT
composer require tymon/jwt-auth
发布配置
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
执行此命令会在 app/config 下生成 jwt.php 的配置文件。
在此请注意一个地方,在 jwt.php 中有个配置项:
'ttl' => env('JWT_TTL', 60),
这里代表的意思是 token 过期的时间,默认为一小时。一般情况下不建议进行更改,因为 token 的时间越长,危险系数就越高。如果是测试的话,可以根据实际情况进行更改。一个小时的时间明显是无法满足实际使用需求,尤其是给微信端做 api 接口。因此,不更改过期时间,需要做 token 刷新。
生成密钥
执行:php artisan jwt:secret
提示:
jwt-auth secret [CHZqhRMbuoUjkQ4iiZIhazbcRLmIsqL5QmYxeIGpWaMuJoaf7ip0v1uteuqiUAbW] set successfully.
配置到.env
JWT_SECRET=CHZqhRMbuoUjkQ4iiZIhazbcRLmIsqL5QmYxeIGpWaMuJoaf7ip0v1uteuqiUAbW
<?php
namespace App\Models;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
protected $fillable = [
'name', 'email', 'password'
];
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 [];
}
}
注意:默认的模型为 app/User.php,如果 User 模型位于其他地方,需要在 app/config/auth.php 中进行修改:
修改 / 配置 auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt', //把token改为jwt
'provider' => 'users',//对应用户认证表
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,//指定模型
'table' => 'users',//数据表
],
],
安装 Dingo
https://learnku.com/docs/dingo-api/2.0.0/Installation/1443
composer require dingo/api
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
执行成功后生成一个位于 app/config 下的配置文件 api.php。
配置.env 文件:
#dingo api设置
API_STANDARDS_TREE=prs
#API_PREFIX=api
API_DOMAIN=test-api.com
API_VERSION=v1
API_DEBUG=true
API_SUBTYPE=myapp
基础控制器导入: use Dingo\Api\Routing\Helpers;
use Helpers;
设置路由
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', ['namespace' => 'App\Http\Controllers\V1'], function ($api) {
$api->post('register', 'AuthController@register');
$api->post('login', 'AuthController@login');
$api->post('logout', 'AuthController@logout');
$api->post('refresh', 'AuthController@refresh');
$api->post('me', 'AuthController@me');
$api->get('test', 'AuthController@test');
});