JWT官方安装方法及使用参考

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37035946/article/details/87876284

 

一、安装

通过composer安装

运行以下命令以引入最新版本:

composer require tymon/jwt-auth

添加服务提供商(Laravel 5.4或更低版本)

将服务提供程序添加到配置文件中的providers数组,config/app.php如下所示:

'providers' => [

    ...

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

发布配置

运行以下命令以发布程序包配置文件:

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

您现在应该有一个config/jwt.php文件,允许您配置此程序包的基础知识。


生成密钥

我已经包含了一个帮助器命令来为您生成一个键:

php artisan jwt:secret

这将.env使用类似的内容更新您的文件JWT_SECRET=foobar

它是用于签署令牌的密钥。具体如何发生取决于您选择使用的算法。

 

二、快速开始

在继续之前,请确保已按照LaravelLumen的安装说明安装了包装 。

更新您的用户模型

首先,您需要Tymon\JWTAuth\Contracts\JWTSubject在User模型上实现合同,这需要您实现2个方法getJWTIdentifier()getJWTCustomClaims()

下面的例子可以让你了解它的外观。显然,您应该根据自己的需要进行必要的更改。

扫描二维码关注公众号,回复: 5272292 查看本文章
<?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;

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

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

配置Auth防护

注意:这仅适用于使用Laravel 5.2及更高版本的情况。

config/auth.php文件内部,您需要进行一些更改以配置Laravel以使用jwt防护来为您的应用程序身份验证提供支持。

对文件进行以下更改:

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

...

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

这里我们告诉api警卫使用jwt驱动程序,我们将api防守设置为默认值。

我们现在可以使用Laravel内置的Auth系统,jwt-auth在幕后工作!

添加一些基本认证路由

首先让我们添加一些路由routes/api.php如下:

Route::group([

    'middleware' => 'api',
    'prefix' => 'auth'

], function ($router) {

    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

});

创建AuthController

然后AuthController手动或通过运行artisan命令创建:

php artisan make:controller AuthController

然后添加以下内容:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

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

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

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

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}

您现在应该能够http://example.dev/auth/login使用一些有效的凭据POST到登录端点(例如),并看到如下响应:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
    "token_type": "bearer",
    "expires_in": 3600
}

然后,此令牌可用于向您的应用程序发出经过身份验证的请求。

经过身份验证的请

有很多方法可以通过http发送令牌:

授权标头

Authorization: Bearer eyJhbGciOiJIUzI1NiI...

查询字符串参数

http://example.dev/me?token=eyJhbGciOiJIUzI1NiI...

Post parameter

Cookies

Laravel route parameter

三、Auth Guards

多个 Guards

如果新创建的“api”防护未设置为默认防护,或者您已定义多个防护来处理身份验证,则应在调用auth()时指定防护。

  $token = auth('api')->attempt($credentials);

attempt()

如果新创建的“api”防护未设置为默认防护,或者您已定义多个防护来处理身份验证,则应在调用auth()时指定防护。

// Generate a token for the user if the credentials are valid
$token = auth()->attempt($credentials);

这将返回jwt或 null

login()

记录用户并为其返回一个jwt

// Get some user from somewhere
$user = User::first();

// Get the token
$token = auth()->login($user);

user()

获取当前经过身份验证的用户。

// Get the currently authenticated user
$user = auth()->user();

如果用户未经过身份验证,null则会返回。

userOrFail()

获取当前经过身份验证的用户或抛出异常。

try {
    $user = auth()->userOrFail();
} catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
    // do something
}

如果未设置用户,则将Tymon\JWTAuth\Exceptions\UserNotDefinedException抛出a

logout()

将用户注销 - 这将使当前令牌无效并取消设置经过身份验证的用户。

auth()->logout();

// Pass true to force the token to be blacklisted "forever"
auth()->logout(true);

refresh()

刷新令牌,使当前令牌无效

$newToken = auth()->refresh();

// Pass true as the first param to force the token to be blacklisted "forever".
// The second parameter will reset the claims for the new token
$newToken = auth()->refresh(true, true);

invalidate()

使令牌无效(将其添加到黑名单)

auth()->invalidate();

// Pass true as the first param to force the token to be blacklisted "forever".
auth()->invalidate(true);

tokenById()

根据给定用户的ID获取令牌。

$token = auth()->tokenById(123);

payload()

获取原始JWT有效负载

$payload = auth()->payload();

// then you can access the claims directly e.g.
$payload->get('sub'); // = 123
$payload['jti']; // = 'asfe4fq434asdf'
$payload('exp') // = 123456
$payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc

validate()

验证用户的凭据

if (auth()->validate($credentials)) {
    // credentials are valid
}

更高级的用法

添加自定义声明

$token = auth()->claims(['foo' => 'bar'])->attempt($credentials);

明确设置标记

$user = auth()->setToken('eyJhb...')->user();

显式设置请求实例

$user = auth()->setRequest($request)->user();

覆盖令牌ttl

$token = auth()->setTTL(7200)->attempt($credentials);

 JWT官方手册

猜你喜欢

转载自blog.csdn.net/qq_37035946/article/details/87876284