Lumen 5.7 配置 jwt-auth 1.0

Lumen 5.7 配置 jwt-auth 1.0

通过composer安装jwt-auth

composer require tymon/jwt-auth:"^1.0@dev"
注意:jwt-auth 0.5版本未对lumen做封装

配置

修改的bootstrap/app.php相关配置

1、去掉$app->withFacades(); 以及 auth 认证相关的注释

$app->withFacades();
$app->withEloquent();

2、去掉 auth 中间件 注释

$app->routeMiddleware([
‘auth’ => App\Http\Middleware\Authenticate::class,
]);

3、去掉appServiceProvider的注释,并且在 AppServiceProvider 中注册 LumenServiceProvider

$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);

//jwt 给 AppServiceProvider 中注册 LumenServiceProvider
$app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);

4、获取jwt配置文件
在 Lumen 项目中,默认没有 config 文件夹,需要在项目根目录创建,并将 vendor 源代码中auth.php 复制出来,并修改如下

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => env('AUTH_GUARD', 'api'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "token"
    |
    */

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

    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        //
    ],

];

5、 JWT 协议需要用到 secret,所以需要生成一个 secret

php artisan jwt:secret

jwt-auth应用

这里用默认的user模型
1、user模型

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable;
    protected $table = 'xxx';//你的表名

    /**
     * The attributes that are mass assignable.
     * 参与生成的token的字段
     *
     * @var array
     */
    protected $fillable = [
         'ui_phone', 'ui_password',
    ];
    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'ui_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 [];
    }


    public function getAuthIdentifierName()
    {
        return 'ui_id';
    }

    public function getAuthPassword()
    {
        return $this->ui_password;
    }




    protected $primaryKey = 'ui_id';

    public $timestamps = false;

}

2、controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\JWTAuth;


class UserController extends Controller
{
    protected $jwt;
    /**
     * Create a new controller instance
     */
    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }

    public function login(Request $request)
    {
        $params    = $request->all();

        $condition = [
            'ui_phone'  => $params['ui_phone'],
            'password'   => $params['password']
        ];
        if (! $token = $this->jwt->attempt($condition)) {
            var_dump($this->jwt->attempt($condition));exit;
            return response()->json(['user_not_found'], 404);
        }

        return response()->json(compact('token'));

    }

}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页