laravel5.8集成JWT记录

参考: laravel5.8集成JWT记录
参考: JWT 文档

1,安装jwt扩展:

composer require tymon/jwt-auth

2,配置:

2.1,发布配置文件:

# 这条命令会在 config 下增加一个 jwt.php 的配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

2.2, 生成加密密钥:

# 这条命令会在 .env 文件下生成一个加密密钥,如:JWT_SECRET=foobar
php artisan jwt:secret

2.3,用户表结构:

# sql:
CREATE TABLE `users` (
 `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
 `name` varchar(250) NOT NULL COMMENT '用户名',
 `email` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '邮箱',
 `email_verified_at` timestamp(0) NULL DEFAULT NULL COMMENT '邮箱验证时间',
 `password` varchar(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '密码',
 `remember_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
 `created_at` timestamp(0) NULL DEFAULT NULL, `updated_at` timestamp(0) NULL DEFAULT NULL,
 PRIMARY KEY (`id`) USING BTREE,
 UNIQUE INDEX `users_name_unique`(`name`) USING BTREE,
 UNIQUE INDEX `users_email_unique`(`email`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;

# migration:
Schema::create('users', function (Blueprint $table) {
 $table->bigIncrements('id');
 $table->string('name')->unique()->comment('用户名');
 $table->string('email')->unique()->comment('邮箱');
 $table->timestamp('email_verified_at')->nullable()->comment('邮箱验证时间');
 $table->string('password')->comment('密码');
 $table->rememberToken();
 $table->timestamps();
});

2.4,用户模型:

<?php
namespace App\Models;

use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Carbon;
use Tymon\JWTAuth\Contracts\JWTSubject;

/**
 * Class UserModel
 *
 * @package App\Models
 * @property int $id
 * @property string $name 用户名
 * @property string $email 邮箱
 * @property string|null $email_verified_at 邮箱验证时间
 * @property string $password 密码
 * @property string|null $remember_token
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @mixin Eloquent
 */
class UserModel extends Authenticatable implements JWTSubject
{
    protected $table = 'users';

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}
2.5,修改auth.php
#./config/auth.php
//此处为我项目的配置
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'userModel',
        'hash' => false,
    ],
],

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

    'userModel' => [
        'driver' => 'eloquent',
        'model' => \App\Models\UserModel::class,
    ],
],

3,注册登录实现:

3.1,定义路由:
# ./routes/api.php
Route::middleware('auth:api')->post('register', 'LoginController@register')->name('register');

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

3.2,控制器(注册,登录):

<?php
namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;

/**
 * Class AuthController
 * @package App\Http\Controllers
 */
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 JsonResponse
     */
    public function login()
    {
        //$credentials = request(['email', 'password']);  // 第一个参数使用什么都可以, 但必须是唯一值
        $credentials = request(['name', 'password']);
        if (!$token = auth('api')->attempt($credentials)) {
            return newErrorReturn('Unauthorized', 401);
            //return response()->json(['error' => 'Unauthorized'], 401);
        }
        return $this->respondWithToken($token);
    }

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

    /**
     * Log the user out (Invalidate the token).
     * @return JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();
        return newSuccessReturn(null, 'Successfully logged out');
        //return response()->json(['message' => 'Successfully logged out']);
    }

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

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

附: 注册和登录时必须使用同一种加密方式, 默认为Bcrypt算法, 在./config/hashing.php中设置: