Laravel5使用 Jwt-Auth 实现 API 用户认证

jwt-auth 最新版本是 1.0.0 rc.1 版本,已经支持了 **Laravel 5.5 **。若是你使用的是 Laravel 5.5 LTS 版本,能够使用以下命令安装。 不懂LTS版本的可自行百度。 若是你是 Laravel 5.5 如下版本,也推荐使用最新版本,RC.1 前的版本都存在多用户token认证的安全问题。php

composer require tymon/jwt-auth 1.0.0-rc.1
复制代码

添加服务提供商

将下面这行添加至 config/app.php 文件 providers 数组中:前端

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
复制代码

将下面这行添加至 config/app.php 文件 aliases数组中:git

'JWTAuth'=> Tymon\JWTAuth\Facades\JWTAuth::class,
  'JWTFactory'=> Tymon\JWTAuth\Facades\JWTFactory::class,
复制代码

在你的 shell 中运行以下命令发布 配置文件:github

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
复制代码

此命令会在 config 目录下生成一个 jwt.php 配置文件,你能够在此进行自定义配置。shell

生成密钥

php artisan jwt:secret
复制代码

此命令会在你的 .env 文件中新增一行 JWT_SECRET=secretjson

配置 Auth guard

'defaults' => [
    'guard' => 'api',         // 修改成api
    'passwords' => 'users',
],
 
'guards' => [
    'api' => [
        'driver' => 'jwt',     // JWTGuard 实现,源码中为 token,我这改为 jwt 了
        'provider' => 'users',
    ],
],
 
'providers' => [
     'users' => [
          'driver' => 'eloquent',
          'model' => App\Models\User::class, // 根据你model的位置更改
     ],
],
复制代码

更改 Model

<?php
 
namespace App\Models;
 
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
 
class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    protected $table = 'users';
    protected $fillable = ['name', 'password', 'mobile'];
    #定义是否默认维护时间,默认是true.改成false,则如下时间相关设定无效
    public $timestamps = true;
    protected $hidden = [
        'password',
    ];
    /**
     * 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 [];
    }
 
}
复制代码

用户提供帐号密码前来登陆。若是登陆成功,那么我会给前端颁发一个 access _tokenapi

执行以下命令以新建一个中间件:数组

php artisan make:middleware ApiAuth
复制代码

中间件代码 ApiAuth.php 以下:安全

<?php
namespace App\Http\Middleware;
 
 
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use JWTAuth;
 
class ApiAuth
{
    public function handle($request, Closure $next)
    {
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据,并赋值给$user
                return response()->json([
                    'errcode' => 1004,
                    'errmsg' => 'user not found'
 
                ], 404);
            }
        return $next($request);
 
    } catch (TokenExpiredException $e) {
 
            return response()->json([
                'errcode' => 1003,
                'errmsg' => 'token 过时' , //token已过时
            ]);
 
        } catch (TokenInvalidException $e) {
 
            return response()->json([
                'errcode' => 1002,
                'errmsg' => 'token 无效',  //token无效
            ]);
 
        } catch (JWTException $e) {
 
            return response()->json([
                'errcode' => 1001,
                'errmsg' => '缺乏token' , //token为空
            ]);
 
        }
    }
 
}
复制代码

在app\Http\Kernel.php下添加以下代码

protected $routeMiddleware = [
        'api.auth' => \App\Http\Middleware\ApiAuth::class,
 ];
复制代码

如今,咱们能够在 routes/api.php 路由文件中路由来测试一下

Route::post('login', 'IndexController@login');
Route::post('register', 'IndexController@register');
复制代码

控制器代码以下:

use JWTAuth;
 
public function login(Request $request)
{
   // 验证规则,因为业务需求,这里我更改了一下登陆的用户名,使用手机号码登陆
    $rules = [
         'mobile'   => ['required'],
         'password' => 'required|string|min:6|max:20',
    ];
 
    // 验证参数,若是验证失败,则会抛出 ValidationException 的异常
    $params = $this->validate($request, $rules);
 
    // 使用 Auth 登陆用户,若是登陆成功,则返回 201 的 code 和 token,若是登陆失败则返回
    $token = JWTAuth::attempt($params);
    if ($token) {
        return $this->responseData(['access_token' => $token]);
    } else {
        $this->responseError('帐号或密码错误');
    }
 
}
 
public function register(RegisterRequest $request)
{
    $mobile = $request->input('mobile');
    $password = $request->input('password');
    // 注册用户
    $user = User::create([
         'mobile' => $mobile,
         'password' => bcrypt($password),
         'nickname' => encryptedPhoneNumber($mobile)
    ]);
    // 获取token
    $token = JWTAuth::fromUser($user);
     if (!$token) {
         return $this->responseError('注册失败,请重试');
     }
 
     return $this->responseData([
         'access_token' => $token,
         'user' => $user
     ]);
}
复制代码

测试截图以下:

image

image

纯原创,但愿能够对你们有帮助,文章会不断更新,若有疑问或新坑,欢迎评论

相关文章
相关标签/搜索