Welcome Guest, Not a member yet? Register   Sign In
Unable to authenticate user when doing unit testing
#1

(This post was last modified: 10-01-2024, 11:39 AM by Morph. Edit Reason: Cleaned up code )

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?
Reply
#2

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

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

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB