FastAPI——token验证

今天讲一下fastapi中的token验证,其实fastapi自身对于token就有验证的,不过这里需要对用户输入的用户名和密码的参数限制为username,password,这对于我们来说有些限制了,比如我们在写微信小程序,或者APP登录时,我们一般不会去使用这种格式,并且在数据库中存入的参数形式也不一致,这样子对于我们来说就不是很有友好了,所以我们这里选择使用token,在使用的时候,我们需要先导入jwt,使用jwt来进行加密以及验证:

pip install jwt

然后需要使用加密字符,这里我没有使用他们的标准生成密钥方式,这里可以使用:

import os
key = os.urandom(32)

这种方式来进行密钥的生成,规范的生成模式还是以官网的那种方式去生成

def jwt_token(data: dict, expires_delta: timedelta):
    jwt_dict = data.copy()
    expired = datetime.utcnow() + expires_delta
    jwt_dict.update({'exp': expired})
    token = jwt.encode(jwt_dict, key, algorithm="HS256")
    return token

这里我们先不说这个函数的,我们先来说

jwt.encode(jwt_dict, key, algorithm="HS256")
# 这里的jwt_dict 是我们的加密数据以及过期时间等数据组成的字典,这里的key,是我们的加密密钥,然后
# algorithm是加密方式
datetime.utcnow() + expires_delta 
# 这一步是格式化时间 在此之前,我们需要导入 
from datetime import datetime, timedelta

然后我们再回到函数中,data为加密数据,是我们需要再登录时去处理的用户数据,然后expires_delta为过期时间,然后我们再回到我们的接口中去

@api.post("/login", summary='用户登录')
async def user_login(body: Register):
    res = await User.filter(userName=body.userName)
    if len(res) == 0:
        return JSONResponse(status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
                            content=APIResponse(405, None, "用户不存在").set_api_dict())
    else:
        md5password = password_md5(body.passWord)
        password = await User.get(userName=body.userName)
        if md5password == password.passWord:
            token = jwt_token({"userID": password.id}, timedelta(days=3))
            return JSONResponse(status_code=status.HTTP_200_OK, content=APIResponse(200, {"token": token}, "登录成功")
                                .set_api_dict(), headers={"Set-Cookie": "X-token=Bearer "+token})
        else:
            return JSONResponse(status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
                                content=APIResponse(405, None, "用户名或密码有误").set_api_dict())

这里的APIResponse是我自己定义的一个函数,用来处理返回数据的,大家这里可以自行忽略,同时我这里也使用了md5加密的一个形式,在前后端交互中,前端也可以处理加密,后端也可以,这个可以大家自行沟通,并且我这里也只是提供一个逻辑而已 ,后续我们再讲一下token的验证如何处理

  • 23
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用FastAPIToken进行身份验证的示例代码: ```python from fastapi import FastAPI, Depends, HTTPException from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # 模拟用户 fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "fakehashedsecret", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Wonderson", "email": "alice@example.com", "hashed_password": "fakehashedsecret2", "disabled": True, }, } # 获取用户信息 def fake_decode_token(token): user = None if token == "johndoe": user = fake_users_db["johndoe"] return user # 验证token async def get_current_user(token: str = Depends(oauth2_scheme)): user = fake_decode_token(token) if not user: raise HTTPException( status_code=401, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) return user # 验证用户是否被禁用 async def get_current_active_user(current_user: dict = Depends(get_current_user)): if current_user["disabled"]: raise HTTPException(status_code=400, detail="Inactive user") return current_user # 登录获取token @app.post("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): user_dict = fake_users_db.get(form_data.username) if not user_dict: raise HTTPException(status_code=400, detail="Incorrect username or password") user = UserInDB(**user_dict) hashed_password = fake_hash_password(form_data.password) if not hashed_password == user.hashed_password: raise HTTPException(status_code=400, detail="Incorrect username or password") return {"access_token": user.username, "token_type": "bearer"} # 需要验证的路由 @app.get("/users/me") async def read_users_me(current_user: dict = Depends(get_current_active_user)): return current_user ``` 在上面的代码中,我们使用OAuth2PasswordBearer和OAuth2PasswordRequestForm来实现身份验证。我们还定义了一个模拟用户数据库fake_users_db,以及一些用于验证和获取当前用户的函数。最后,我们定义了一个需要验证的路由,即/users/me,它需要一个有效的token才能访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值