Laravel API 认证:JWT 认证 6 个改进

安装 jwt-auth

composer require tymon/jwt-auth

添加服务提供者(如果 Laravel 版本 < 5.5)

添加到 config/app.php 中:

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

发布配置文件

运行如下命令发布配置文件到 config

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

生成 JWT_SECRET

你可以通过运行如下命令自动生成 JWT_SECRET.env 中:

php artisan jwt:secret

更新 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;

    // 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 guard

config/auth.php 文件中配置 JWT

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

...

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

增加一些基本的认证路由

首选在 routes/api.php 中添加路由选项:

Route::group([
    '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

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', 'refresh']]);
    }

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

        if (!$token = auth('api')->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('api')->user());
    }

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

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

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->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('api')->factory()->getTTL() * 60
        ]);
    }
}

然后可以通过 POST 用户认证凭据到 http://example.dev/api/auth/login 来获取 token,你将得到如下内容:

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

这个 token 将可以被用来认证.

认证方式

支持以下两种方式。通过 HTTP 请求来认证:

Authorization header

Authorization: Bearer eyJhbGciOiJIUzI1NiI...

Query string parameter

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

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 7

支持不了6.x版本的laravel,有解决办法吗?

4年前 评论
osang (作者) 4年前

我在生成token的时候已经把token_type设置成空了, 但是前端传给我token的时候 前面还是要拼接Bearer

3年前 评论

上述示例已经测试,都ok。 但是做了一个实验,就是在没有登陆或者登陆但是不传递token的情况下,直接访问 example.dev/api/auth/me。返回给我的是一个html页面,而这个html页面是登陆页面,觉得既然是jwt api的方式,应该不能返回html,而是返回无权限的json相关数据。所以我该如何修改?

不传递token file 传递token file

2年前 评论
sy_dante 1年前

我在请求auth/me的时候,token过期需要刷新,auth('api')->user()的方式,用户信息是不是拿不到,因为tymon/jwt-auth是根据请求头上的token来获取用户的,所以感觉这个tymon/jwt-auth有很大的缺陷

1年前 评论

实验认证jwt的时候报错 "message": "Cannot instantiate interface Lcobucci\JWT\Builder", "status_code": 500, "debug": { "line": 170, "file": "/home/vagrant/code/shopApi/vendor/tymon/jwt-auth/src/Providers/AbstractServiceProvider.php", "class": "Error",

1年前 评论

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