我们基于FastAPI Security系列之生成token(基础篇)往下深入,上篇说到如何生成token;本篇主要讲述,前端用户获取token过程,要先完成用户登录验证,如果验证通过则返回token令牌;前端用户在拿到令牌后,在token有效期内,携带令牌开始愉快的请求其他API数据吧!
完整代码详解 点击这里可以飞向官网 把代码写出文档,下面开始表演
# -*- coding: UTF-8 -*-
from datetime import datetime, timedelta
import jwt
from fastapi import Depends, FastAPI, HTTPException
from starlette import status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jwt import PyJWTError
from passlib.context import CryptContext # passlib 处理哈希加密的包
from pydantic import BaseModel
# to get a string like this run: openssl rand -hex 32
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" # 密钥
ALGORITHM = "HS256" # 算法
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 访问令牌过期分钟
'''用户数据(模拟数据库用户表);账号:johndoe 密码:secret
用于我们稍后验证。'''
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
"disabled": False,
}
}
'''FastAPI参数类型验证模型'''
# token url相应模型
class Token(BaseModel):
access_token: str
token_type: str
# 令牌数据模型
class TokenData(BaseModel):
username: str = None

最低0.47元/天 解锁文章
515

被折叠的 条评论
为什么被折叠?



