diff --git a/src/Controllers/ApiController.php b/src/Controllers/ApiController.php index e1e863c9..f75873cf 100644 --- a/src/Controllers/ApiController.php +++ b/src/Controllers/ApiController.php @@ -41,10 +41,19 @@ function actionIndex() $authorization = Craft::$app->request->headers->get('authorization'); preg_match('/^(?:b|B)earer\s+(?.+)/', $authorization, $matches); - $token = Token::findOrAnonymous(@$matches['tokenId']); + + try { + $token = Token::findOrAnonymous(@$matches['tokenId']); + } + catch (\Exception $e) { + + $response->headers->add('Status', 401); + $response->headers->add('WWW-Authenticate', 'Bearer'); + return $this->asJson(['error' => ['status' => 401, 'message' => 'token_invalid']]); + } if ($user = $token->getUser()) { - $response->headers->add('Authorization', 'TOKEN ' . CraftQL::getInstance()->jwt->tokenForUser($user)); + $response->headers->add('Authorization', 'Bearer ' . CraftQL::getInstance()->jwt->tokenForUser($user)); } if ($allowedOrigins = CraftQL::getInstance()->getSettings()->allowedOrigins) { @@ -125,7 +134,6 @@ function actionIndex() // You must set the header to JSON, otherwise Craft will see HTML and try to insert // javascript at the bottom to run pending tasks - $response = \Craft::$app->getResponse(); $response->headers->add('Content-Type', 'application/json; charset=UTF-8'); return $this->asJson($result); diff --git a/src/Models/Token.php b/src/Models/Token.php index d8c84079..1908c6a9 100644 --- a/src/Models/Token.php +++ b/src/Models/Token.php @@ -4,7 +4,6 @@ use Craft; use craft\db\ActiveRecord; -use Firebase\JWT\ExpiredException; use GraphQL\Error\UserError; use markhuot\CraftQL\CraftQL; @@ -59,12 +58,7 @@ public static function findOrAnonymous($token=false) // If the token matches a JWT format if (preg_match('/[^.]+\.[^.]+\.[^.]+/', $token)) { - try { - $tokenData = CraftQL::getInstance()->jwt->decode($token); - } - catch (ExpiredException $e) { - throw new UserError('The token has expired'); - } + $tokenData = CraftQL::getInstance()->jwt->decode($token); $user = \craft\elements\User::find()->id($tokenData->id)->one(); $token = Token::forUser($user); return $token; @@ -193,4 +187,4 @@ function canMatch($regex): bool { return count($scopes) > 0; } -} \ No newline at end of file +}