CodeIgniter Forums
Unable to authenticate user when doing unit testing - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Unable to authenticate user when doing unit testing (/showthread.php?tid=91746)



Unable to authenticate user when doing unit testing - Morph - 10-01-2024

I'm building an API with CodeIgniter v4.5.5.

I'm also using Shield and using the token based authentication.

I can successfully register and login a user through a POST request using a REST client.

However, I am unable to login the user in a unit test. Other POST requests (like registering a new user) work fine in unit tests.

This is the section of code which authenticates a user:

PHP Code:
// Attempt to login
$result auth()->attempt($validData);

// If login fails
if (!$result->isOK()) {
    throw new UnauthorizedException(['auth' => 'Unable to log you in. Please check your credentials.']);


Works fine with a REST client.

This is the output of dump($result) when attempting to POST to /login in my unit tests:

Code:
CodeIgniter\Shield\Result^ {#498
  #success: false
  #reason: "Every request must have a bearer token in the Authorization header."
  #extraInfo: null
}

So when attempting the POST request through the framework , Shield is refusing to authenticate due to a bearer token missing.

This endpoint (/login) is excluded from the tokens filter in the Filters.php configuration.

How do I workaround this with a POST request to /login?


RE: Unable to authenticate user when doing unit testing - kenjis - 10-03-2024

> Every request must have a bearer token in the Authorization header.

Why don't you send a bearer token in the Authorization header?


RE: Unable to authenticate user when doing unit testing - Morph - 10-03-2024

Because the endpoint is excluded from the tokens filter in the global routing config.

Also I have tried passing a bearer token as a "hack" - it still does not work.

It is a bug in Shield.