honojs/hono

Basic Auth not asking for login details, it instantly returns 401

Closed this issue · 2 comments

What version of Hono are you using?

4.3.2

What runtime/platform is your app running on?

Cloudflare Workers

What steps can reproduce the bug?

app.get("/auth", basicAuth({ username: "user", password: "pass" }), (c) => {
  return c.json({
    message: "success",
    status: 200,
  });
});
app.onError((err, c) => {
  if (err instanceof HTTPException) {
    console.log("http exception");
    const responseStatus = err.getResponse();
    return c.json(
      {
        message: responseStatus.statusText,
        status: err.status,
      },
      err.status,
    );
  } else {
    console.error("An error has been thrown: " + err);
    return c.json(
      {
        message: "Internal Server Error",
        status: 500,
      },
      500,
    );
  }
});

The app logs 'http exception', and returns

{"message":"Unauthorized","status":401}

In previous versions of Hono, it asked the user for basic auth, now instead, it instantly returns Unauthorized without asking for basic auth.

What is the expected behavior?

It should ask for basic auth.

What do you see instead?

No basic auth being asked, and unauthorized being returned instantly.

Additional information

No response

Fixed it by manually adding the WWW-Authenticate header.

I don't think this is "fixed" if the docs don't say that I need to put the header.

Basically if is used with onError this way to handle the exception is needed
#952 (comment)