蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

RESTful API进阶:JWT、条件缓存、限流与架构边界:独立实例

PYTHONPython3.12、PyJWT2.15.1、SQLite;Node原生fetch及Edge浏览器观察单独保存advance.py
advance.py18 行
from client import API
import sys,json,time,secrets,jwt,os
api=API(sys.argv[1]);user=api.user_fixture('条件请求学习者');path='/api/users/'+str(user['id']);first=api.call('GET',path);tag=first['headers']['etag'];cached=api.call('GET',path,headers={'If-None-Match':tag});api.expect(cached,304);assert cached['body'] is None and 'private' in first['headers']['cache-control']
api.expect(api.call('PATCH',path,{'phone':'demo-new'},headers={'If-Match':'"stale-version"'}),412)
api.expect(api.call('PATCH',path,{'phone':'demo-new'},headers={'If-Match':tag}),200)
key=os.environ['MBSKY_DEMO_SIGNING_KEY'];stamp=int(time.time());expired=jwt.encode({'sub':str(api.user['id']),'iss':'urn:mbsky:rest-demo','aud':'mbsky-rest','iat':stamp-120,'exp':stamp-60},key,algorithm='HS256')
api.expect(api.call('GET','/api/users/profile',headers={'Authorization':'Bearer '+expired}),401)
for change in [{'iss':'urn:other-issuer'},{'aud':'other-audience'},{'exp':None}]:
 claims={'sub':str(api.user['id']),'iss':'urn:mbsky:rest-demo','aud':'mbsky-rest','iat':stamp,'exp':stamp+60};claims.update(change)
 if change.get('exp','present') is None:claims.pop('exp')
 invalid=jwt.encode(claims,key,algorithm='HS256');api.expect(api.call('GET','/api/users/profile',headers={'Authorization':'Bearer '+invalid}),401)
wrong_algorithm=jwt.encode({'sub':str(api.user['id']),'iss':'urn:mbsky:rest-demo','aud':'mbsky-rest','iat':stamp,'exp':stamp+60},key,algorithm='HS384');api.expect(api.call('GET','/api/users/profile',headers={'Authorization':'Bearer '+wrong_algorithm}),401)

parts=api.token.split('.');parts[1]=parts[1][:-1]+('A' if parts[1][-1]!='A' else 'B');api.expect(api.call('GET','/api/users/profile',headers={'Authorization':'Bearer '+'.'.join(parts)}),401)
responses=[api.call('GET','/api/limited') for _ in range(3)];assert [r['status'] for r in responses]==[200,200,429];assert int(responses[-1]['headers']['retry-after'])>0
api.expect(api.call('DELETE',path),204)
print(json.dumps({'etag_status':304,'stale_write':412,'expired_and_tampered_tokens':401,'limit_statuses':[r['status'] for r in responses],'third_party_oauth_redis_graphql':'not executed, retained separately'}))
本例需在 Python3.12、PyJWT2.15.1、SQLite;Node原生fetch及Edge浏览器观察单独保存 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python3.12、PyJWT2.15.1、SQLite;Node原生fetch及Edge浏览器观察单独保存

入口文件:projects/rest-lab/advance.py

预期结果与验证条件观察提示
  • 本章明确的输入及错误分支断言对应真实服务状态
  • 没有修改现有网站数据,也未发送真实邮件或通知

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:RESTful API

课程关联工程包(登记关联10章) · 含当前章节或实例 · mbskycom202611a547.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习