用python代码,用fastapi实现登录接口和token验证,给出示例代码
时间: 2023-03-14 17:29:49 浏览: 81
以下是Python代码示例,使用FastAPI实现登录接口和token验证:from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import jwtapp = FastAPI()# 用户信息
users = {
"foo": {
"username": "foo",
"full_name": "Foo Bar",
"email": "foo@example.com",
"hashed_password": "fakehashedsecret"
}
}# 用户定义模型
class User(BaseModel):
username: str
password: str# 登录接口
@app.post("/login")
async def login(user: User):
username = user.username
if username in users:
if users[username]["hashed_password"] == user.password:
access_token = jwt.encode({"sub": username}, "secret", algorithm="HS256")
return {"access_token": access_token, "token_type": "bearer"}
else:
raise HTTPException(status_code=400, detail="Incorrect username or password")
else:
raise HTTPException(status_code=400, detail="Incorrect username or password")# token验证
@app.get("/users/me")
async def read_users_me(token: str = Header(...)):
credentials_exception = HTTPException(
status_code=401,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, "secret", algorithms=["HS256"])
username = payload.get("sub")
if username is None:
raise credentials_exception
token_data = users[username]
except jwt.PyJWTError:
raise credentials_exception
return token_data