laravel5.6集成auth-jwt

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhaozonglu/article/details/79919847

阅读本文之前,先参考下文,配置laravel登录认证
http://laravelacademy.org/post/8900.html

安装auth-jwt

  composer require tymon/jwt-auth:dev-develop --prefer-source

配置 config/app.php

providers数组中添加

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

aliases数组中添加

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

发布配置文件

执行命令

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

生成秘钥

执行命令

php artisan jwt:secret

配置 config/auth.php

修改auth guard

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

更改 App\users

修改User类,实现JWTSubject接口

class User extends Authenticatable implements JWTSubject{
//...
    public function getJWTIdentifier()
    {
        // TODO: Implement getJWTIdentifier() method.
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        // TODO: Implement getJWTCustomClaims() method.
        return [];
    }
}

随便写一个Controller


namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use JWTAuth;

class AuthenticateController extends Controller
{
    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');
        try{
            $token = JWTAuth::attempt($credentials);
            if (!$token){
                return response()->json(['error'=>'invalid_credentials'],401);
            }
        } catch(JWTException $e){
            return response()->json(['error'=>'invalid_credentials'],500);
        }
        return response()->json(compact('token'));
    }
}

添加一条路由信息

Route::get('/auth', 'User\AuthenticateController@authenticate');

生成token

浏览器访问 http://host:port/auth?email=xxxx&password=xxxx

实现以上步骤即可laravel5.6中集成auth-jwt

展开阅读全文

没有更多推荐了,返回首页