main.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from fastapi import FastAPI, Depends
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.openapi.utils import get_openapi
  4. from fastapi.security import HTTPBearer
  5. from app.api import router
  6. from app.core.auth import verify_token
  7. from app.core.config import settings
  8. app = FastAPI(title=settings.app_name)
  9. # -----------------------
  10. # CORS(可选)
  11. # -----------------------
  12. app.add_middleware(
  13. CORSMiddleware,
  14. allow_origins=["*"],
  15. allow_methods=["*"],
  16. allow_headers=["*"],
  17. )
  18. # -----------------------
  19. # 路由注册
  20. # -----------------------
  21. # 公共路由,不鉴权
  22. app.include_router(router.public_router, prefix="/api")
  23. # 需要鉴权的路由
  24. app.include_router(
  25. router.protected_router,
  26. prefix="/api",
  27. dependencies=[Depends(verify_token)]
  28. )
  29. # -----------------------
  30. # Swagger 支持 Bearer Token
  31. # -----------------------
  32. def custom_openapi():
  33. if app.openapi_schema:
  34. return app.openapi_schema
  35. openapi_schema = get_openapi(
  36. title=app.title,
  37. version="1.0.0",
  38. description="API documentation",
  39. routes=app.routes,
  40. )
  41. # 添加全局 Bearer
  42. openapi_schema["components"]["securitySchemes"] = {
  43. "BearerAuth": {
  44. "type": "http",
  45. "scheme": "bearer",
  46. "bearerFormat": "JWT"
  47. }
  48. }
  49. for path in openapi_schema["paths"].values():
  50. for method in path.values():
  51. method["security"] = [{"BearerAuth": []}]
  52. app.openapi_schema = openapi_schema
  53. return app.openapi_schema
  54. app.openapi = custom_openapi