* @throws ApiAuthorizationException The token couldn't be validated.
*/
protected function checkToken($request) {
- $jwt = $request->getHeaderLine('jwt');
- if (empty($jwt)) {
+ if (! $request->hasHeader('Authorization')) {
throw new ApiAuthorizationException('JWT token not provided');
}
throw new ApiAuthorizationException('Token secret must be set in Shaarli\'s administration');
}
- ApiUtils::validateJwtToken($jwt, $this->conf->get('api.secret'));
+ $authorization = $request->getHeaderLine('Authorization');
+
+ if (! preg_match('/^Bearer (.*)/i', $authorization, $matches)) {
+ throw new ApiAuthorizationException('Invalid JWT header');
+ }
+
+ ApiUtils::validateJwtToken($matches[1], $this->conf->get('api.secret'));
}
/**
$env = Environment::mock([
'REQUEST_METHOD' => 'GET',
'REQUEST_URI' => '/echo',
- 'HTTP_JWT'=> 'jwt',
+ 'HTTP_AUTHORIZATION'=> 'Bearer jwt',
]);
$request = Request::createFromEnvironment($env);
$response = new Response();
}
/**
- * Invoke the middleware without an invalid JWT token (debug):
+ * Invoke the middleware with an invalid JWT token header
+ */
+ public function testInvalidJwtAuthHeaderDebug()
+ {
+ $this->conf->set('dev.debug', true);
+ $mw = new ApiMiddleware($this->container);
+ $env = Environment::mock([
+ 'REQUEST_METHOD' => 'GET',
+ 'REQUEST_URI' => '/echo',
+ 'HTTP_AUTHORIZATION'=> 'PolarBearer jwt',
+ ]);
+ $request = Request::createFromEnvironment($env);
+ $response = new Response();
+ /** @var Response $response */
+ $response = $mw($request, $response, null);
+
+ $this->assertEquals(401, $response->getStatusCode());
+ $body = json_decode((string) $response->getBody());
+ $this->assertEquals('Not authorized: Invalid JWT header', $body->message);
+ $this->assertContains('ApiAuthorizationException', $body->stacktrace);
+ }
+
+ /**
+ * Invoke the middleware with an invalid JWT token (debug):
* should return a 401 error Unauthorized - with a specific message and a stacktrace.
*
* Note: specific JWT errors tests are handled in ApiUtilsTest.
$env = Environment::mock([
'REQUEST_METHOD' => 'GET',
'REQUEST_URI' => '/echo',
- 'HTTP_JWT'=> 'bad jwt',
+ 'HTTP_AUTHORIZATION'=> 'Bearer jwt',
]);
$request = Request::createFromEnvironment($env);
$response = new Response();