5

安装

composer create-project --prefer-dist laravel/laravel sample "5.5.*"

安装依赖

composer install

安装jwt-auth

composer require tymon/jwt-auth

or
在composer.json中添加 `"tymon/jwt-auth": "^1.0.0-rc.2",`
终端:composer update

config/app.phpproviders

'providers' => [

    ...

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

终端运行:php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"会产生config/jwt.php的配置文件

再运行:php artisan jwt:secret生成key

建Model

运行:

php artisan make:model Models/Admin -m
php artisan make:model Models/User -m

database/migrations下
迁移文件中

    **admins:**
Schema::create('admins', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->string('avatar')->nullable();
    $table->timestamps();
});
    **users:**
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->string('avatar')->nullable();
    $table->timestamps();
});

修改Model(USer和Admin是一样的)

<?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 [];
    }
}

config/auth.php中配置,找到对应的修改成自己的

'guards' => [

'web' => [
    'driver' => 'session',
    'provider' => 'users',
],

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

'admin' => [
    'driver' => 'jwt',
    'provider' => 'admins',
],

],

'providers' => [

'users' => [
    'driver' => 'eloquent',
    'model' => App\Models\User::class,
    'table' => 'users',
],

'admins' => [
    'driver' => 'eloquent',
    'model' => App\Models\Admin::class,
    'table' => 'admin_users'
],

],

路由

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');

});

控制器(关键)

运行:php artisan make:controller AdminController创建控制器
注:此处主要是用了guard('admin')来区分要调用的表和Model这里是在auth.php中配置的

<?php

namespace App\Http\Controllers;

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

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

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

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

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

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

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

中间键

由于使用了多表认证,所以不能使用jwt自带的中间键auth:api or jwt.auth,我自己建了一个中间键[myauth]来做路由验证。
在app/Http/Middleware下新建

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AuthMiddleware {
    public function handle($request, Closure $next)
    {

        try {
            $user = auth()->guard('admin')->userOrFail();
            if(!$user) {
                return response()->json(['message' => 'jwt 无效'], 401);
            }
        } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
            return response()->json(['message' => 'jwt 无效'], 401);
        }
        return $next($request);
    }
}

然后在app/Http/Kernel$routeMiddleware下添加
protected $routeMiddleware = [

    ...

    'cors' => \App\Http\Middleware\ClientRequestCors::class, //自定义的跨域中间键
    'myauth' => \App\Http\Middleware\AuthMiddleware::class,

    ...

];

在路由和Controller下的构造函数调用。

免责

由于时间关系,没有在PostMan截图了,参考此文章的小伙伴自行进行测试
下面例子源用了很多jwt-auth文档代码


羊爸爸
935 声望41 粉丝

很懒,没什么好写的