在python fastapi中利用jwt实现接口鉴权,核心做法是引入`pyjwt`库生成和解析令牌,并结合fastapi的依赖注入系统(dependency injection)创建自定义依赖项来拦截请求。具体而言,你需要编写一个函数从http header中提取bearer token,使用密钥解码并验证其有效性,若验证通过则返回用户信息供路由使用,否则抛出http 401异常。这样做能确保只有持有合法令牌的客户端才能访问受保护的资源。

create_access_token函数如何生成包含过期时间的Token
生成Token的关键在于配置载荷(Payload)中的过期时间(exp)。通常使用`datetime`模块计算当前时间加上设定的有效期,并将其存入载荷字典中。随后调用`jwt.encode()`方法,传入载荷、加密密钥以及算法类型(如HS256),即可得到签名的字符串。该过程确保了Token具有时效性,防止长期有效带来的安全风险。

import jwt
from datetime import datetime, timedelta, timezone
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
decode_token依赖如何处理无效或过期的Token
在处理请求时,依赖项需要负责解析Token并处理可能的异常。如果Token格式错误、签名不匹配或已过期,`jwt.decode()`会抛出特定异常。开发者应捕获这些异常并转换为FastAPI的HTTPException,状态码设为401,以拒绝非法请求。这种机制保证了鉴权的严谨性,任何不符合规范的Token都会被直接拦截。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials")
return username
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials")
当Token载荷中缺少sub字段时鉴权结果是什么
如果在解码过程中发现载荷中缺少必需的sub(subject)字段,或者该字段值为None,鉴权流程将明确失败。在上述实现的decode_token逻辑中,代码显式检查了username是否为None。如果是,程序会主动抛出一个带有“Invalid authentication credentials”消息的401 Unauthorized异常。这意味着即使Token签名正确且未过期,只要关键身份信息缺失,接口依然会拒绝访问,从而保障数据安全性。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










