laravel jwt多用户支持

2020-10-10  本文已影响0人  噫那里有条咸鱼

前后端分离,但是后台需要为不同的前端提供api支持,所以做了一下jwt的多用户切换。


环境:laravel5.5+


composer require tymon/jwt-auth:1.0
php artisan migrate

再随便添加两条数据

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret

接口要求我们实现两个方法:

1、getJWTIdentifier —— 返回模型的 id,一般直接使用 $this->getKey() 返回模型主键

2、getJWTCustomClaims —— 返回数组,存放自定义的数据用于放在 Token 中,可以先返回空数组。

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    protected $table = 'user';

    //================== JWT配置 start ====================
    //这里我将手机号作为身份标识
    public function getJWTIdentifier()
    {
        return $this->mobile;
    }
    //可以加入一些额外的自定义数据,加入到载荷中
    public function getJWTCustomClaims()
    {
        return [
            'user_id' => $this->id,
            'sub'     => $this->mobile,
        ];
    }
    //================== JWT配置 end ====================

}

...
    'defaults' => [
        'guard'     => 'wechat_api',
        'passwords' => 'users',
    ],

    'guards' => [
        'wechat_api' => [
            'driver'   => 'jwt',
            'provider' => 'users',
            'hash'     => false,
        ],
    ],
...
$credentials = ['mobile' => '18612345678'];
$token = auth('wechat_api')->attempt($credentials);
auth('wechat_api')->logout();
$token = auth('wechat_api')->refresh();

ps:刷新需要配置一下config/jwt.php

//token过期时间,默认60分钟
'ttl' => env('JWT_TTL', 60),
//多长时间内,jwt可以再次被刷新,默认20160分钟(14天)
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
//return App/Models/User
auth()->user()
Route::any('/test', function () {
    return auth('wechat_api')->attempt(['mobile' => '18612345678']);
});

访问api/test:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC95dWVsYWkuZWJvb2tcL2FwaVwvd2VjaGF0XC90ZXN0IiwiaWF0IjoxNjAyMjM3Nzk5LCJleHAiOjE2MDIyNDEzOTksIm5iZiI6MTYwMjIzNzc5OSwianRpIjoicVZ1RXNPd0dnaVFOZWpwTSIsInN1YiI6IjE4NjE1ODY1Nzk2IiwidXNlcl9pZCI6MX0.G5Nw_YQxU6ujnA5aYc36f80Ig_WNiNczInk64W_b7ow"
}

多用户切换

php artisan make:model Admin
namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class Admin extends Authenticatable implements JWTSubject
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}
php artisan make:migration --table=admin

迁移文件字段自行添加,之后执行迁移:

php artisan migrate
...
'guards' => [
        ...
        'admin' => [
            'driver' => 'jwt',
            'provider' => 'admins',
        ],
    ],
    'providers' => [
        ...
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
...
//普通用户登录
Route::post('user/login', function(Request $request) {
    $credentials = $request->only('mobile');
    if (!$token = auth('wechat_api')->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
    return response()->json(['token' => $token]);
});
//普通用户验证
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:wechat_api');

//后端用户登录
Route::post('admin/login', function(Request $request) {
    $credentials = $request->only('email', 'password');
    if (!$token = auth('admin')->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
    return response()->json(['token' => $token]);
});
//后端用户验证
Route::get('/admin', function (Request $request) {
    return $request->user();
})->middleware('auth:admin');
上一篇 下一篇

猜你喜欢

热点阅读