我在Firebase JWT项目中使用了Lumen,但是我不确定在令牌无效时是否返回自定义json响应。我正在使用默认的Authenticate.php中间件。
我不知道我该使用中间件还是像throw new Exception('token not provided');
这样的异常?
AuthServiceProvider.php (下面是我当前的代码)是解码令牌的好地方吗?
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\ServiceProvider;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Exception;
class AuthServiceProvider extends ServiceProvider
{
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
$token = $request->bearerToken();
if(!$token) {
// Unauthorized response if token not there
throw new Exception('token not provided');
}
try {
$credentials = JWT::decode($token, env('JWT_SECRET'), ['HS256']);
} catch(ExpiredException $e) {
return response()->json([
'error' => 'token expired'
], 400);
} catch(Exception $e) {
return response()->json([
'error' => 'token error'
], 400);
}
return User::find($credentials->sub);
});
}
}