Laravel 5.5 使用 Jwt-Auth 实现 API 用户认证、刷新令牌(一)

本文介绍了在Laravel 5.5中使用Jwt-Auth实现API用户认证和刷新令牌的步骤,包括安装、配置、自定义认证中间件和异常处理。详细讲解了JWT的工作原理,并提供了具体的代码示例和路由设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:

新项目,采用前后端分离的模式,前端使用 Vue.js,后端使用 Laravel 5.5构建 Api 服务,用户认证的包使用 jwt-auth 。本次博客会分4步完成,

  1. Laravel 5.5 使用 Jwt-Auth 实现 API 用户认证、刷新令牌(一)
  2. Laravel–CORS 扩展包完美解决前后端分离应用跨域请求
  3. vue+axios 拦截器实现统一token
  4. Laravel 5.5 使用 Jwt-Auth 实现 API多 用户、多字段认证、刷新令牌(二)

概述:

JWT(JSON Web Token)是一个非常轻巧的规范。这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息。一个JWT实际上就是一个字符串,它由三部分组成,头部、载荷与签名。
更详细讲解地址:https://laravelacademy.org/post/3640.html

安装

1.个人使用laravel5.5 使用composer require tymon/jwt-authphp artisan jwt:generate报错,所以使用以下命令

composer require tymon/jwt-auth:dev-develop --prefer-source

2.安装完成后在配置文件 config/app.php 中注册服务提供者和别名:

'providers' => [
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class
]

'aliases' => [
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
]

3.发布配置文件

在你项目根目录运行如下命令发布生成config\ jwt.php 的配置文件:

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

4.在发布的配置中生成key:

此命令会在你的 .env 文件中新增一行 JWT_SECRET=secret。

php artisan jwt:secret

5.配置 Auth guard

在 config/auth.php 文件中,你需要将 guards/driver 更新为 jwt:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

6.更改 Model
如果需要使用 jwt-auth 作为用户认证,我们需要对我们的 User 模型进行修改,实现一个接口,变更后的 User 模型如下:

<?php

namespace App;

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

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * 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',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    p
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值