Skip to content

A free open source IT asset/license management system

Check for bearer token along wth expectsJson

snipe9c8c180e8ad3
diff --git a/app/Http/Middleware/CheckUserIsActivated.php b/app/Http/Middleware/CheckUserIsActivated.php
index 7fb79c14e8..b7f357a8db 100644
--- a/app/Http/Middleware/CheckUserIsActivated.php
+++ b/app/Http/Middleware/CheckUserIsActivated.php
@@ -61,7 +61,16 @@ class CheckUserIsActivated
// "known token, disabled account" case from an unknown
// token. From the client's point of view this reads
// identically to a rejected / expired token.
- if ($request->expectsJson()) {
+ //
+ // Bearer-token check is a second signal alongside
+ // expectsJson() because some API clients don't set the
+ // Accept header (curl without -H, older SDKs, misconfigured
+ // integrations). Falling through to Auth::logout() on a
+ // bearer-authenticated request would call logout() on
+ // Passport's TokenGuard, which doesn't define that method,
+ // and produce a 500 (BadMethodCallException) instead of
+ // the intended 401.
+ if ($request->expectsJson() || $request->bearerToken()) {
return response()->json(
Helper::formatStandardApiResponse('error', null, trans('general.unauthorized')),
Response::HTTP_UNAUTHORIZED,
diff --git a/tests/Feature/Authentication/CheckUserIsActivatedApiTest.php b/tests/Feature/Authentication/CheckUserIsActivatedApiTest.php
index 28728bb9dd..5724de93a6 100644
--- a/tests/Feature/Authentication/CheckUserIsActivatedApiTest.php
+++ b/tests/Feature/Authentication/CheckUserIsActivatedApiTest.php
@@ -88,4 +88,28 @@ class CheckUserIsActivatedApiTest extends TestCase
$this->assertStringNotContainsStringIgnoringCase('activat', (string) ($body['messages'] ?? ''));
$this->assertStringNotContainsStringIgnoringCase('disabled', (string) ($body['messages'] ?? ''));
}
+
+ /**
+ * Rollbar regression pin: a Python client hitting /api/v1/hardware
+ * with a bearer token but without an Accept: application/json
+ * header used to fatal with BadMethodCallException. The middleware
+ * fell past its expectsJson() check (Python's requests library
+ * doesn't set Accept by default) and called Auth::logout() on
+ * Passport's TokenGuard, which doesn't define that method.
+ *
+ * A bearer token is now a sufficient signal that the caller is on
+ * the API surface, so the middleware returns a JSON 401 instead
+ * of trying to terminate a session that doesn't exist.
+ */
+ public function test_bearer_authenticated_request_without_accept_header_returns_json_not_500(): void
+ {
+ Passport::actingAs(User::factory()->create(['activated' => 0]));
+
+ $response = $this
+ ->withHeader('Authorization', 'Bearer fake-token-value')
+ ->get(route('api.assets.index'));
+
+ $response->assertUnauthorized();
+ $this->assertSame('error', $response->json('status'));
+ }
}