安装
将"tymon/jwt-auth": "1.0.0-beta.1" 添加到 composer.json 中,执行 composer update
或者

composer require tymon/jwt-auth 0.5.*

Providers
config/app.php 中在 providers 里添加

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

Class Aliases
config/app.php 中在 aliases 里添加

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class

修改认证驱动
修改config/auth.php,将 api 的 driver 修改为 jwt。如下:

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

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

修改模型文件 User.php
在最后加入这两个方法:

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

路由 web.php

Route::get('register', 'ApiController@Register');
Route::get('login', 'ApiController@Login');

Route::group(['middleware' => 'auth.jwt'], function () {
    Route::get('userdetails', 'ApiController@UserDetails');
});

中间件 authJWT.php
记得要去kernel.php后将新建的中间件添加进去

namespace App\Http\Middleware;
use Closure;

class AuthJWT
{
    public function handle($request, Closure $next)
    {
        $user = auth()->user();

        if (is_null($user))
            return response()-> json(['code'=>100]);

        if($user['type'] == 1)
        {
            // 用户禁止登陆
            return response()-> json(['code'=>101,'msg'=>'用户被禁止']);
        }

        return $next($request);
    }
}

控制器Controller/ApiController.php
登陆生成token

public function Login(Request $request)
{
    $input = request(['email', 'password']);

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

    return response()->json(['result' => $token]);
}

获取用户信息

public function UserDetails()
{
    return response()->json(auth()->user()->toArray());
}