Laravel-JWT

271 阅读1分钟

1.安装jwt-auth

composer require tymon/jwt-auth 1.*@rc

2.发布配置文件

这条命令会在 config 下增加一个 jwt.php 的配置文件

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

3.生成密钥

php artisan jwt:secret

4.更改 User 模型

新增 getJWTIdentifier() , getJWTCustomClaims() 两个方法

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

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

5.注册两个 Facade

这两个 Facade 不是必须的,但是使用它们会给你的代码编写带来一点便利。

config.php

'aliases' => [
        ...
        // 添加以下两行
       'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
       'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],

如果你不使用这两个 Facade,你可以使用辅助函数 auth () auth() 是一个辅助函数,返回一个 guard,暂时可以看成 Auth Facade

// 如果不用 Facade,你可以这么写
auth('api')->refresh();
// 用 JWTAuth Facade
JWTAuth::parseToken()->refresh();

6.修改 auth.php

config/auth.php

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

    'api' => [
        'driver' => 'jwt',      // 原来是 token 改成jwt
        'provider' => 'users',
    ],
],

7.注册路由

routes/api.php

Route::post('login', 'AuthController@login');
Route::middleware("auth:api")->group(function () {
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::get('me', 'AuthController@me');
});

8.创建 token 控制器

php artisan make:controller AuthController

AuthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use JWTAuth;

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

//    public function login(){
//
//        $data = request(['name','password']);
////         dd($data);
//
//
//        if($token = auth('api')->attempt($data)){
//
//            return $this->respondWithToken($token);
//        }
//
//
//        return response()->json(['error'=>'Unauthorized'],401);
//    }

    public function login(Request $request)
    {
        $data = request(['name','password']);
//        dd($input);
        $jwt_token = null;
        if (!$jwt_token = JWTAuth::attempt($data)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid name or Password',
            ], 401);
        }

        return response()->json([
            'success' => true,
            'token' => $jwt_token,
        ]);
    }


    public function me()
    {
        // dd(11);
        return response()->json(auth('api')->user());
    }

    public function logout(){

        $data = auth('api')->logout();

        return response()->json(['msg'=>'success','data'=>$data]);
    }
}


用户表密码字段使用 Bcrypt 加密

Bcrypt密码生成计算器