laravel 使用 jwt

laravel 使用 jwt


网上各种使用jwt的版本,也是经历了许多坑之后,实践出来的结果。

首先我们将为我们的新身份验证防护使用tymondesigns / jwt-auth(docs)

composer require tymon/jwt-auth "1.0.*"

jwt-auth composer包有一个我们可以发布的配置文件:

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

config / jwt.php中生成一个新的配置文件。下一步是生成密钥。我们将使用此密钥签署所有令牌。

php artisan jwt:secret

此命令将为JWT_SECRET我们的.env文件添加一个值。为了使用这个jwt-auth软件包,我们的用户模型(或我们用于验证的任何模型)必须实现该JWTSubject接口。该接口有两种方法,我们可以在这里看到:

<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tymon\JWTAuth\Contracts;

interface JWTSubject
{
    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier();

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims();
}

为了实现接口,您需要在类中提供该接口的所有方法。这意味着对于我们的User模型来实现这个接口,它需要有一个getJWTIdentifier方法和一个getJWTCustomClaims方法。

在此处阅读有关JSON Web令牌结构的更多信息:[https://jwt.io/introduction/]

主题声明将是对我们用户的参考。Eloquent 在我们的模型上提供了一个getKey方法,它返回记录主键的值。对于Laravel中的默认用户表,主键是id列。对于自定义声明方法,我们不会担心这一点,而是返回一个空数组。
我们还想确保每当我们保存密码时,我们都会保存哈希版本。我们可以通过使用Laravel Mutator来实现这一点,这样每当我们将值保存到password列时,我们总是保存散列版本。

<?php

namespace App\Model;

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

class Web_member_data extends Authenticatable implements JWTSubject
{

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

    public function getJWTCustomClaims()
    {
        return [];
    }
    
    ...

(注:上面是laravel自带的user模型,你可以在任何你需要的模型中添加这些)

在我们的config / auth.php文件中,我们需要指定我们想要使用此包提供的 jwt guard

'defaults' => [
      'guard' => 'api',
      'passwords' => 'users',
    ],

    ...

    'guards' => [
     'api' => [
            'driver' => 'jwt',
            'provider' => 'memberdata',
        ],

    ...

'providers' => [
        'memberdata' => [
            'driver' => 'eloquent',
            'model' => App\Model\Web_member_data::class,
        ],
]
    ],

所以我们的默认auth后卫是“api”后卫,而后卫使用jwt驱动程序。这使我们主要使用内置的Laravel auth功能,但由幕后的jwt-auth驱动程序提供支持。
你需要手动创建路由(登录,注册),建立这些路线后,让我们看看如何实现这些方法。其中大部分直接来自tymondesigns / jwt-auth docs
首先,在routes / api.php中定义路由并使用创建相应的控制器。

php artisan make:controller AuthController
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $user = User::create([
             'email'    => $request->email,
             'password' => $request->password,
         ]);

        $token = auth(‘api’)->login($user);

        return $this->respondWithToken($token);
    }

    public function login()
    {
        $credentials = request(['email', 'password']);
        // 这里,他用的是email和password,你可以改成你需要的u_name和u_pwd(举个例子)
        if (! $token = auth(‘api’)->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    public function logout()
    {
        auth(‘api’)->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type'   => 'bearer',
            'expires_in'   => auth()->factory()->getTTL() * 60
        ]);
    }
}

另外,它本身自带的验证密码参数是password,你需要手动修改他的验证参数,可以在你使用的模型中修改
这个很关键,当时我就卡在这里

public function getAuthPassword()
{
    return $this->u_pwd;
}

其中的u_pwd就是你需要验证的数据库的密码字段
就这样,完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值