美文网首页
laravel jwt多用户支持

laravel jwt多用户支持

作者: 噫那里有条咸鱼 | 来源:发表于2020-10-10 16:34 被阅读0次

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


环境:laravel5.5+


  • 安装扩展tymon/jwt-auth
composer require tymon/jwt-auth:1.0
  • 生成user表(用默认的迁移文件就行了)
php artisan migrate

再随便添加两条数据

  • 发布jwt配置
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
  • 生成jwt secret
php artisan jwt:secret
  • 修改一下 User 模型,需要实现扩展包提供的接口Tymon\JWTAuth\Contracts\JWTSubject

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

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 ====================

}

  • 结合 laravel auth, 配置config/auth.php
...
    '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();
  • 刷新jwt
$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),
  • 获取当前jwt对应的用户
//return App/Models/User
auth()->user()
  • 测试一下
    routes/api.php
Route::any('/test', function () {
    return auth('wechat_api')->attempt(['mobile' => '18612345678']);
});

访问api/test:

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

多用户切换

  • 再新建一个adminmodel
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
  • 修改config/auth.php配置
...
'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');

相关文章

网友评论

      本文标题:laravel jwt多用户支持

      本文链接:https://www.haomeiwen.com/subject/cqdjpktx.html