laravel5.5 + jwt-auth:dev-developphp
composer require tymon/jwt-auth:dev-develop --prefer-source
config/app.php中增長provider者和aliases,寫入對應的數組laravel
//provider 'Tymon\JWTAuth\Providers\LaravelServiceProvider' //aliases 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth' 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory'
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" --force
命令會生成 config/jwt.php 配置文件git
php artisan jwt:secret
會在.env 添加JWT_SECRETgithub
JWT_SECRET=z4Pv7YXnOOodpuGO7FOy1vLsxxxxicmoU
<?php namespace App; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject { use Notifiable; // Rest omitted for brevity /** * 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 []; } }
config/auth.php中修改看守器api
'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ], ... 'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
Route::get('/signin', "AuthController@signin"); //這裏分配了中間件,驗證是否登陸 Route::group(['middleware' => ['auth:api']], function(){ Route::get('menu', 'MenuController@index'); });
public function signin(Request $request) { if($token = JWTAuth::getToken()){ try{ JWTAuth::invalidate($token); }catch(\Exception $e){ } } $credentials = $request->only('name', 'password'); if (! $token = JWTAuth::attempt($credentials)) { return $this->error('用戶名或密碼錯誤'); } return $this->success(['token' => $token]); }
參考資料數組
https://github.com/tymondesigns/jwt-auth/wiki/Installationapp
http://jwt-auth.readthedocs.io/en/docs/quick-start/#update-your-user-modelcomposer
https://github.com/tymondesigns/jwt-auth/issues/1298ide
因爲使用老版產生的問題ui
Class Tymon\JWTAuth\Providers\JWT\Namshi does not exist
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" --force
Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an instance of Tymon\JWTAuth\Contracts\JWTSubject
更改user model
<?php namespace App; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject { use Notifiable; // Rest omitted for brevity /** * 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 []; } }