sqlite 登录以访问此站点www.example.com需要授权http://0.0.0.0:8080您与此站点的连接不安全

a1o7rhls  于 2023-03-13  发布在  SQLite
关注(0)|答案(1)|浏览(795)

我有一个用fastapi开发的网络应用程序,当我尝试登录时,banner会弹出,我不知道需要使用什么凭据,当我按取消键时,我得到这个:{“详细信息”:“未验证”}
IDE中的信息:
信息:127.0.0.1:60849-“POST /登录HTTP/1.1”401未经授权
登录功能:

# login
@app.get('/login', response_class=HTMLResponse)
async def login_page(request: Request):
   return templates.TemplateResponse("login.html", {"request": request})

@app.post('/login')
async def login(request: Request, email: str = Form(...), password: str = Form(...)):
   user = curr.execute('SELECT * FROM user WHERE email = ?', (email,))

   if user:
       curr.execute('SELECT password FROM user WHERE email = ?', (email,))
       password_hash = curr.fetchone()[0]

       if check_password_hash(password_hash, password):
           request.session['logged_in'] = True
           return RedirectResponse(url='/index')
       else:
           raise HTTPException(status_code=400, detail='Incorrect password, try again.')
   else:
       raise HTTPException(status_code=400, detail='Email does not exist.')
kokeuurv

kokeuurv1#

您正在访问http://localhost:8080,而您应该使用https://localhost:8080。请注意,https://代替了http://

**编辑:**浏览器会话验证

您看到的横幅很可能是基于浏览器的身份验证提示,这意味着Web服务器需要身份验证才能访问受保护的资源(在本例中为/login端点),但浏览器无法提供有效的凭据。
由于您从服务器收到401 Unauthorized响应,这意味着身份验证凭据丢失或不正确。服务器希望客户端在请求中发送有效凭据。在您的情况下,看起来您没有发送任何身份验证凭据,这就是您看到身份验证提示的原因。
要解决此问题,您需要更改登录函数,使其返回带有有效身份验证凭据的响应。由于您使用FastAPI,因此可以使用会话来管理身份验证。您可以存储已在会话中通过身份验证的用户的详细信息,并使用这些详细信息来检查用户在发出另一个请求时是否仍通过身份验证。
以下是使用会话管理身份验证的登录函数的更新版本:

from fastapi import Depends, FastAPI, HTTPException, Request, Form, Response, status
from fastapi.responses import HTMLResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.templating import Jinja2Templates
from werkzeug.security import check_password_hash

app = FastAPI()
security = HTTPBasic()
templates = Jinja2Templates(directory="templates")

# mock user data
users = {
    "john@example.com": {
        "password": "password",
        "name": "John Doe",
    }
}

# session dependency
async def get_session(request: Request):
    session = request.session
    if not session.get("user"):
        session["user"] = None
    return session

# login
@app.get('/login', response_class=HTMLResponse)
async def login_page(request: Request):
   return templates.TemplateResponse("login.html", {"request": request})

# login form submit
@app.post("/login")
async def login(
    request: Request,
    response: Response,
    credentials: HTTPBasicCredentials = Depends(security),
    session: dict = Depends(get_session),
):
    user = users.get(credentials.username)

    if not user or not check_password_hash(user["password"], credentials.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )

    session["user"] = user["name"]
    return {"message": "Logged in successfully!"}

在这个更新版本的登录函数中,我们使用HTTPBasic安全方案从请求中提取用户名和密码,然后使用这些凭据通过与伪造的用户数据字典进行比较来验证用户的身份。
如果凭据无效,我们将引发一个HTTPException,其中包含一个401 Unauthorized状态代码和一个WWW-Authenticate头,以指示客户机需要提供有效的凭据。
如果凭据有效,我们将用户名存储在会话中并返回成功消息。
注意,我们使用get_session依赖项从请求中获取会话对象,并使用Depends参数将此会话对象作为依赖项传递给登录函数,这确保我们可以访问函数中的会话对象,并保存已通过身份验证的用户的信息。

相关问题