laravel8.x--JWT

composer安装jwt-auth

composer require tymon/jwt-auth

config/app.php注册服务提供者

'providers' => [
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
'aliases' => [
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
]

发布生成配置文件

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

执行后config下自动生成jwt.php文件

生成JWT_SECRET

php artisan jwt:secret

执行后会在.env中自动生成:

JWT_SECRET=IVYIoZuMhB2vUE6HQQOinyYhSL2DMhuVxsRNVAqkEzO3W3Qe9nG3G5SIH6GQG1Bd

config/auth.php中配置guards

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
    ],

更改model文件app\Models\User.php

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * 获取会储存到 jwt 声明中的标识
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 返回包含要添加到 jwt 声明中的自定义键值对数组
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return ['role' => 'user'];
    }
}

router/api.php中创建路由信息

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::group([
    'prefix' => 'v1/auth'
], function () {
    Route::post('login', [\App\Http\Controllers\AuthController::class, 'login'])->name('login');
    Route::post('logout', [\App\Http\Controllers\AuthController::class, 'logout'])->name('logout');
    Route::post('refresh', [\App\Http\Controllers\AuthController::class, 'refresh'])->name('refresh');
    Route::get('user', [\App\Http\Controllers\AuthController::class, 'user'])->name('user');
});

创建相应控制器AuthController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;

class AuthController extends Controller
{
    protected $userModel;

    public function __construct ()
    {
        $this->userModel = new User();

        $this->middleware('auth:api',['except' => ['login']]);
    }

    public function login ()
    {
        $credentials = request(['nickname', 'password']);
        if (!$token = auth('api')->attempt($credentials)) {
            return json_encode(['code' => 500, 'msg'  => '登录失败,请检查用户名或密码']);
        }
        return $this->respondWithToken($token);
    }

    public function respondWithToken ($token) {
        return json_encode([
            'code' => 200,
            'msg' => '成功',
            'data' => [
                'access_token' => $token,
                'token_type'   => 'bearer',
                'expires_in'   => auth('api')->factory()->getTTL() * 60
            ]
        ]);
    }

    public function user ()
    {
        return json_encode([
            'code' => 200,
            'msg'  => '成功',
            'data' => auth('api')->user()
        ]);
    }

    public function logout ()
    {
        auth('api')->logout();
        return json_encode(['code' => 200, 'msg' => '退出成功']);
    }

    public function refresh ()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }
}

测试

  • login

laravel8.x--jwt

  • user

laravel8.x--jwt

  • logout

laravel8.x--jwt

  • refresh

laravel8.x--jwt

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!