Python fastAPI 的 FastAPI-Login 库,登录后请求接口老是提示 “Not authenticated”

五月朝露 · 2020年04月09日 · 最后由 buggg 回复于 2020年04月26日 · 3883 次阅读
from fastapi import Depends
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_login.exceptions import InvalidCredentialsException

import uvicorn

from fastapi import FastAPI

SECRET = "your-secret-key"

app = FastAPI()

from fastapi_login import LoginManager
manager = LoginManager(SECRET, tokenUrl='/auth/token')

fake_db = {'johndoe@e.mail': {'password': 'hunter2'}}

@manager.user_loader
def load_user(email: str):  # could also be an asynchronous function
    user = fake_db.get(email)
    return user

@app.post('/auth/token')
def login(data: OAuth2PasswordRequestForm = Depends()):
    print(data)
    email = data.username
    password = data.password

    user = load_user(email)  # we are using the same function to retrieve the user
    if not user:
        raise InvalidCredentialsException  # you can also use your own HTTPException
    elif password != user['password']:
        raise InvalidCredentialsException

    access_token = manager.create_access_token(
        data=dict(sub=email)
    )
    return {'access_token': access_token, 'token_type': 'bearer'}

@app.get("/hello")   #  就是这里
def read_root(user=Depends(manager)):
    return {"Hello": "World","esvdgsjv":"wertghvqw3etghvbc"}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

运行后,postman 登录接口 127.0.0.1/auth/token,登录后获得 token。可是 127.0.0.1/hello 这个接口怎么请求的?token 放那里?怎么放的?

共收到 1 条回复 时间 点赞

放 Authentication 里面

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册