首页 > 其他分享 >Fastapi之OAuth2认证

Fastapi之OAuth2认证

时间:2023-04-28 14:33:42浏览次数:44  
标签:username status OAuth2 Fastapi 认证 current token user password

1.基于用户名密码认证

from typing import Optional

from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

from pydantic import BaseModel
from starlette import status

tokens = APIRouter()

oauth2_schema = OAuth2PasswordBearer(tokenUrl="/token")
"""
客户端会向该接口发送一个带用户名和密码的请求,得到一个token
OAuth2PasswordBearer并不会创建相应的URL路径操做,只是指明客户端用来请求Token的地址
当请求到达时,FastAPI会检测请求的Authorization头信息,或者头信息的内容不是Bearer token,它会返回401状态码(UNAUTHORIZED)
"""

# 模拟数据库数据
fake_users_db = {
    "jack": {
        "username": "jack",
        "full_name": "Jack",
        "email": "[email protected]",
        "hashed_password": "d2h3k2n4h23bn4b23h53mbn3bm24mmn43",
        "disabled": True
    },
    "lucy": {
        "username": "lucy",
        "full_name": "Lucy",
        "email": "[email protected]",
        "hashed_password": "9d34lk2n6h23le4b23h53mbn3bm24mg2nhk",
        "disabled": False
    }
}


class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None


class UserInDB(User):
    hashed_password: str


@tokens.post("/", summary="获取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=status.HTTP_404_NOT_FOUND,
            detail="User does not exists"
        )
    user = UserInDB(**user_dict)
    print(user.hashed_password)
    hashed_password = fake_hash_password(form_data.password)  # 将前端提交密码进行加密后与数据库密码比对
    if hashed_password != user.hashed_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect username or password"
        )
    return {"access_token": user.username, "token_type": "bearer"}

2.基于token获取用户信息

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from starlette import status

tokens = APIRouter()


# 模拟加密函数
pwd_factory = {
    "password1": "d2h3k2n4h23bn4b23h53mbn3bm24mmn43",
    "password2": "9d34lk2n6h23le4b23h53mbn3bm24mg2nhk"
}


# 模拟加密
def fake_hash_password(password: str):
    return pwd_factory[password]


def get_user(username: str):
    """
    获取用户信息
    :param username:
    :return:
    """
    # 测试数据token直接使用的就是用户名,所以这块直接当作用户名使用,来查找用户
    # 真实情况下可能会使用混合加密,将用户名作为载体混淆在token信息中,需要解析出用户名后再查找用户
    if username:
        user_dict = fake_users_db[username]
        return User(**user_dict)


def fake_decode_token(token):
    """从token中解析用户信息"""
    user = get_user(token)
    return user


async def get_current_user(token: str = Depends(oauth2_schema)):
    """依赖OAuth2认证接口"""
    user = fake_decode_token(token)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"}
        )
    return user


async def get_active_user(current_user: User = Depends(get_current_user)):
    if current_user.disabled:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Inactive user"
        )
    return current_user


@tokens.get("/current_users", summary="获取当前用户")
async def read_user_info(current_user: User = Depends(get_active_user)):
    """获取活跃的用户"""
    return current_user

标签:username,status,OAuth2,Fastapi,认证,current,token,user,password
From: https://www.cnblogs.com/puffer/p/16416728.html

相关文章

  • elasticsearch 7.4.2设置安全认证
    1、修改elasticsearch.yml文件,重启ES#允许head插件等访问的相关设置http.cors.enabled:truehttp.cors.allow-origin:"*"http.cors.allow-headers:Authorization,X-Requested-With,Content-Length,Content-Typehttp.cors.allow-credentials:true#是否启用es的安全设置,启......
  • Shiro安全认证
    学习视频:https://www.bilibili.com/video/BV1Wb411V7uk学习网站:https://www.w3cschool.cn/shiro/介绍ApacheShiro是Java的一个安全框架Shiro可以完成:认证、授权、加密、会话管理、与Web集成、缓存等。Authentication:身份认证/登录Authorization:授权,即权限验证Se......
  • 3C强制性认证条件,3C证书监督审查
    3C强制性认证由于国家对产品质量的重视和环保要求,3C认证已成为各企业或工厂的一致要求,但从认证到认证仍有许多标准,大多数企业仍有些模糊,所小化妆在这里解释下3C认证批准条件以及如何保持认证,希望对您有所帮助。批准颁发3C认证证书的条件1.申请人具有法人地位,在认证过程中履行职责和......
  • 认证失败处理器与注销成功处理器
    认证失败处理器  packagecom.example.springsecurity.handler;importorg.springframework.security.core.AuthenticationException;importorg.springframework.security.web.authentication.AuthenticationFailureHandler;importorg.springframework.ste......
  • SpringSecurity从入门到精通:认证成功处理器&认证失败处理器
    认证成功处理器  认证失败处理器  ......
  • django token 认证 简单记录
    classUser(AbstractUser):username=models.CharField(max_length=20,unique=True,primary_key=True,verbose_name="用户名")email=models.EmailField(max_length=256,null=False,verbose_name="邮箱",blank=True)pass......
  • drf之三大组件(认证组件、权限组件、频率组件)
    目录环境准备创建相关的表,models.py创建登录样例配置路由认证组件BaseAuthentication创建认证组件创建测试样例总结1.创建认证组件2.局部使用(只在一个视图类中使用,使用后会影响当前视图类中管理的所有接口)3.全局使用(对所有接口都生效)4.局部禁用权限组件BasePermission环境......
  • adobe认证证书
    Adobe认证证书分为产品技能认证和职业技能认证:产品技能认证AdobeCertifiedProfessionalPhotoshop认证专家AdobeCertifiedProfessionalIllustrator认证专家AdobeCertifiedProfessionalInDesign认证专家AdobeCertifiedProfessionalPremierePro认证专家AdobeCertifiedP......
  • adobe国际认证证书有用吗?
    获得Adobe国际认证证书,对于是否是创意设计师都可以赋予他们以下优势:①证明专业技能:Adobe证书是一种权威的认证,可以证明设计师在使用Adobe软件方面具有专业技能。这可以帮助设计师在求职过程中脱颖而出,提高竞争力。②提高工作效率:Adobe软件是设计师必备的工具,掌握这些工具的高效使用......
  • P.22-认证配置详解、P.23-权限系统的作用、P.24-授权基本流程
    P.22-认证配置详解在SecurityConfig下进行修改@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//创建BCryptPasswordEncoder注入容器@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEn......