前言
當前官方Lumen最新版本:7.1.3
項目根目錄:/home/wwwroot/blog
項目域名:api.kimphp.com
安裝JWT
composer require tymon/jwt-auth
修改app.php及AppServiceProvider.php
編輯blog/bootstrap/app.php
取消以下代碼註釋:
.
$app->withFacades();
$app->withEloquent();
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
編輯blog/app/Providers/AppServiceProvider.php
在register方法內添加:
$this->app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
如下圖:
配置env
添加配置項
編輯blog/.env
添加如下配置:
#JWT身份驗證密鑰,添加完配置後,執行以下命令php artisan jwt:secret將會自動獲取JWT身份驗證密鑰並會自動填充
JWT_SECRET=
#JWT公鑰,也可以是JWT公鑰文件所在路徑
JWT_PUBLIC_KEY=
#JWT私鑰,也可以是JWT私鑰文件所在路徑
JWT_PRIVATE_KEY=
#JWT密碼短語,也就是密碼,如果不設置,留空即可
JWT_PASSPHRASE=
#JWT令牌有效時長(分鐘),默認60分鐘,留空則代表令牌永不過期,如果留空則必須從required_claims中移除exp
JWT_TTL=60
#指定JWT令牌刷新的有效時長(分鐘),默認2周,留空則代表令牌獲得無限刷新時間
JWT_REFRESH_TTL=20160
#JWT簽名令牌的哈希算法
JWT_ALGO=HS256
#指定JWT令牌驗證期間允許的時間偏差秒數,適用於(`iat`、`nbf`、`exp`)這三種斷言,默認是0
JWT_LEEWAY=0
#啓用黑名單,要使令牌失效,必須啓用黑名單。如果不希望或不需要此功能,請將其設置爲false。
JWT_BLACKLIST_ENABLED=true
#黑名單寬限期,當用同一個JWT發出多個併發請求時,由於每一個請求都會再生令牌,其中一些可能會失敗,以秒爲單位設置寬限期以防止並行請求失敗。
JWT_BLACKLIST_GRACE_PERIOD=0
如下圖:
生成JWT_SECRET
執行以下命令,將會自動獲取JWT身份驗證密鑰並會自動填充到.env對應配置中
php artisan jwt:secret
增加auth.php配置並編輯
複製blog\vendor\laravel\lumen-framework\config\auth.php到blog\config\auth.php
修改blog\config\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' => [
//
],
];
增加登錄控制器AuthController.php
純lumen下AuthController.php示例
新建blog\app\Http\Controllers\AuthController.php
代碼如下:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\JWTAuth;
class AuthController extends Controller
{
protected $jwt;
public function __construct(JWTAuth $jwt)
{
$this->jwt = $jwt;
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);
try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['user_not_found'], 404);
}
} catch (TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (JWTException $e) {
return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode());
}
return response()->json(compact('token'));
}
}
lumen+dingo/api下AuthController.php示例
新建blog\app\Http\Controllers\v1\AuthController.php
代碼如下:
<?php
namespace App\Http\Controllers\v1;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\JWTAuth;
class AuthController extends Controller
{
protected $jwt;
public function __construct(JWTAuth $jwt)
{
$this->jwt = $jwt;
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);
try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['user_not_found'], 404);
}
} catch (TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (JWTException $e) {
return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode());
}
return response()->json(compact('token'));
}
}
增加路由
純lumen下路由示例
<?php
$router->post('auth/login', 'AuthController@login');
lumen+dingo/api下路由示例
<?php
$api = app('Dingo\Api\Routing\Router');
/** @var Dingo\Api\Routing\Router $api */
$api->version('v1', ['namespace' => 'App\Http\Controllers\v1'],function ($api) {
/** @var Dingo\Api\Routing\Router $api */
$api->post('auth/login', 'AuthController@login');
$api->get('hello_world','HelloWorldController@index');
});