Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct handling of malformed tokens with compliant 401 response according to RFC 6750 #118

Open
wants to merge 3 commits into
base: user-tokens
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/Controllers/ApiController.php
Original file line number Diff line number Diff line change
@@ -41,10 +41,19 @@ function actionIndex()

$authorization = Craft::$app->request->headers->get('authorization');
preg_match('/^(?:b|B)earer\s+(?<tokenId>.+)/', $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);
10 changes: 2 additions & 8 deletions src/Models/Token.php
Original file line number Diff line number Diff line change
@@ -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;
}
}
}