honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.25k stars 515 forks source link

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

Closed JustJoostNL closed 4 months ago

JustJoostNL commented 4 months ago

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

JustJoostNL commented 4 months ago

Fixed it by manually adding the WWW-Authenticate header.

hectorAguero commented 3 months ago

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 https://github.com/honojs/hono/issues/952#issuecomment-1453630369