tiangolo / fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production
https://fastapi.tiangolo.com/
MIT License
73.13k stars 6.16k forks source link

Basic auth accepts wrong password as a correct one! #11759

Closed rugved-bodke-stigya closed 1 week ago

rugved-bodke-stigya commented 1 week ago

Privileged issue

Issue Content

from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette.status import HTTP_401_UNAUTHORIZED

app = FastAPI()

security = HTTPBasic()

def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    if credentials.username != "foo" or credentials.password != "password":
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

@app.get("/users/me")
def read_current_user(username: str = Depends(get_current_username)):
    return {"username": username}

import uvicorn

uvicorn.run(app, host="0.0.0.0", port=8000)

Hi I'm struggling to place a basic auth, and using the latest fastapi version but still the app is working with any random string

JavierSanchezCastro commented 1 week ago

That's not an issue.

On the other side, your code is working as expected, I'm going to assume, that when you said that is working with any random string, you're referring to the swagger green button for "Authorize". Remember, that button has no verification after you enter your credentials. If you run your code without putting anything in Authorize beforehand, you're going to see something like:

image

And that input has the verification of your code to check username and password.

Check this for more info: https://fastapi.tiangolo.com/advanced/security/http-basic-auth/