-
Notifications
You must be signed in to change notification settings - Fork 469
[Docs][MDX] Add python backend integration #874
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
… templates, and added new document to the docs-platform.yml
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughAdds a new Python backend integration doc describing token flow and two server-side verification strategies (JWT local verification and REST API verification), framework examples (Flask, FastAPI, Django), environment variables, error-handling patterns, and performance guidance. Also updates docs navigation to include the new page. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor U as User (Client)
participant FE as Client App
participant BE as Python Backend
participant SA as Stack Auth API
U->>FE: Sign in
FE->>FE: user.getAuthJson() -> accessToken
FE->>BE: HTTP request with X-Stack-Access-Token header
alt JWT Verification (local)
BE->>BE: Fetch/cache JWKS (PyJWKClient)
BE->>BE: Verify JWT (ES256, aud checks)
BE-->>FE: 200 + user payload
else REST API Verification (remote)
BE->>SA: GET /api/v1/users/me (x-stack-access-token)
SA-->>BE: Verified user data
BE-->>FE: 200 + user data
end
note over BE: Errors -> 401/403 (MISSING_TOKEN / INVALID_TOKEN)\nor 5xx (SERVER_ERROR)
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a tick 8000 et on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
docs/docs-platform.yml (1)
111-113
: Remove Python from the cross-platform nav entry (docs/docs-platform.yml:111–113)
Drop"python"
so this entry readsplatforms: ["next", "react", "js"]
, avoiding duplication with the Python-only entry at line 288.
🧹 Nitpick comments (4)
docs/templates-python/concepts/backend-integration.mdx (4)
6-6
: Clarify that verification can be JWT or REST, not always a server call.
The opening sentence implies you must call Stack Auth on every request. Reword to reflect both options.-To authenticate your Python server endpoints, you need to send the user's access token in the headers of the request to your server, and then make a request to Stack Auth's server API to verify the user identity. +To authenticate your Python server endpoints, send the user's access token in the request headers. Then either verify it locally via JWT (no external call) or verify it via Stack Auth's REST API.
37-38
: Remove unused dependency/import in JWT section.
requests
isn’t used in the JWT example; PyJWKClient doesn’t require it. Keep it in the REST section only.-pip install PyJWT[crypto] requests +pip install PyJWT[crypto]-import requests
Also applies to: 44-44
130-133
: Standardize header casing in FastAPI and use an alias.
Header names are case-insensitive, but be consistent with other examples and docs.-async def get_current_user(x_stack_access_token: Optional[str] = Header(None)): +async def get_current_user(x_stack_access_token: Optional[str] = Header(None, alias="X-Stack-Access-Token")):
226-228
: Standardize header casing in REST helper example.
Align with “X-Stack-Access-Token” used elsewhere.- user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ - 'x-stack-access-token': access_token - }) + user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ + 'X-Stack-Access-Token': access_token + })
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
docs/docs-platform.yml
(1 hunks)docs/templates-python/concepts/backend-integration.mdx
(1 hunks)docs/templates-python/meta.json
(1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/templates-python/concepts/backend-integration.mdx
[grammar] ~304-~304: There might be a mistake here.
Context: ...external requests, but limited user data - REST API Verification: Slower, require...
(QB_NEW_EN)
[grammar] ~305-~305: There might be a mistake here.
Context: ..., but provides complete user information - Caching: Consider caching JWKs and use...
(QB_NEW_EN)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: docker
- GitHub Check: restart-dev-and-test
- GitHub Check: all-good
- GitHub Check: build (22.x)
- GitHub Check: lint_and_build (latest)
- GitHub Check: build (22.x)
- GitHub Check: docker
- GitHub Check: setup-tests
- GitHub Check: Security Check
🔇 Additional comments (4)
docs/templates-python/meta.json (1)
12-12
: LGTM — page wired into Python templates.
Placement under the Concepts section looks consistent with templates-python.docs/templates-python/concepts/backend-integration.mdx (2)
49-49
: Clarify JWKS URL service and scope. Which “Stack Auth” endpoint are you targeting—Stack Exchange’sstackauth.com
or your own API atapi.stack-auth.com
? Once confirmed, verify the correct host, path, and project-scoping for the JWKS URL and update accordingly.
55-61
: Remove issuer verification suggestion from JWT examples
Stack Auth access tokens are opaque and do not include an iss claim; verifying an issuer is not applicable. Applies to the code examples at lines 55–61, 90–96, 136–141, and 172–177.Likely an incorrect or invalid review comment.
docs/docs-platform.yml (1)
288-290
: LGTM — Python-only registration matches the new templates page.
This aligns the Python navigation with the new doc.
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
♻️ Duplicate comments (1)
docs/templates-python/concepts/backend-integration.mdx (1)
200-203
: Use consistent header casing: X-Stack-Access-Token (matches earlier examples).Align with the earlier “Frontend code” snippet and prior review feedback.
- user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ - 'x-stack-access-token': access_token - }) + user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ + 'X-Stack-Access-Token': access_token + })- 'x-stack-access-token': access_token + 'X-Stack-Access-Token': access_tokenAlso applies to: 343-344
🧹 Nitpick comments (2)
docs/templates-python/concepts/backend-integration.mdx (2)
130-133
: FastAPI: set explicit header alias for clarity.Make the header name explicit to avoid surprises and mirror the docs’ casing.
- async def get_current_user(x_stack_access_token: Optional[str] = Header(None)): + async def get_current_user( + x_stack_access_token: Optional[str] = Header(None, alias="X-Stack-Access-Token") + ):
442-442
: Minor grammar fix.-Choose the appropriate method based on your endpoint's requirements: +Choose the appropriate method based on your endpoints' requirements:
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
docs/templates-python/concepts/backend-integration.mdx
(1 hunks)docs/templates-python/meta.json
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/templates-python/meta.json
🧰 Additional context used
🪛 LanguageTool
docs/templates-python/concepts/backend-integration.mdx
[grammar] ~442-~442: There might be a mistake here.
Context: ...d based on your endpoint's requirements: - Use JWT for high-performance endpoin...
(QB_NEW_EN)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: restart-dev-and-test
- GitHub Check: docker
- GitHub Check: lint_and_build (latest)
- GitHub Check: docker
- GitHub Check: setup-tests
- GitHub Check: all-good
- GitHub Check: build (22.x)
- GitHub Check: build (22.x)
- GitHub Check: Security Check
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (4)
docs/templates-python/concepts/backend-integration.mdx (4)
201-204
: Standardize header casing in examples.Use the same “X-Stack-Access-Token” casing used elsewhere for consistency. HTTP headers are case-insensitive, but docs should be consistent.
- user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ - 'x-stack-access-token': access_token - }) + user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ + 'X-Stack-Access-Token': access_token + })
308-312
: Match header casing when calling Stack Auth API.Align with earlier suggestion for consistent docs.
- 'x-stack-access-type': 'server', - 'x-stack-project-id': stack_project_id, - 'x-stack-publishable-client-key': stack_publishable_client_key, - 'x-stack-secret-server-key': stack_secret_server_key, + 'X-Stack-Access-Type': 'server', + 'X-Stack-Project-Id': stack_project_id, + 'X-Stack-Publishable-Client-Key': stack_publishable_client_key, + 'X-Stack-Secret-Server-Key': stack_secret_server_key,
331-336
: Replicate issuer and claim checks in the complete example.Keep security posture consistent with the earlier snippet.
payload = jwt.decode( access_token, signing_key.key, algorithms=["ES256"], - audience=stack_project_id + audience=stack_project_id, + issuer=f"https://api.stack-auth.com/api/v1/projects/{stack_project_id}", + options={"require": ["exp", "iat", "iss", "aud", "sub"]} )
57-63
: Add issuer validation and require critical JWT claims.Strengthen verification by checking issuer and requiring standard claims.
payload = jwt.decode( access_token, signing_key.key, algorithms=["ES256"], - audience="<your-project-id>", - + audience="<your-project-id>", + issuer="https://api.stack-auth.com/api/v1/projects/<your-project-id>", + options={"require": ["exp", "iat", "iss", "aud", "sub"]}, + # Optional clock skew tolerance: + # leeway=60, )
🧹 Nitpick comments (2)
docs/templates-python/concepts/backend-integration.mdx (2)
298-326
: Validate required env vars before use; fix placement/indent.Ensure all needed env vars are present before building URLs or sending requests; also unindent the guard so it clearly runs at import time.
stack_secret_server_key = os.getenv("STACK_SECRET_SERVER_KEY") +if not stack_project_id: + raise RuntimeError("STACK_PROJECT_ID is not set") +if not stack_publishable_client_key: + raise RuntimeError("STACK_PUBLISHABLE_CLIENT_KEY is not set") +if not stack_secret_server_key: + raise RuntimeError("STACK_SECRET_SERVER_KEY is not set") + def stack_auth_request(method, endpoint, **kwargs): @@ return res.json() - if not stack_project_id: - raise RuntimeError("STACK_PROJECT_ID is not set") - # JWT verification setup jwks_client = PyJWKClient(f"https://api.stack-auth.com/api/v1/projects/{stack_project_id}/.well-known/jwks.json")
291-297
: Use a shared Session with retry/backoff for REST calls.Reduces connection overhead and adds resiliency.
import jwt import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry from jwt import PyJWKClient from jwt.exceptions import InvalidTokenError from enum import Enum @@ -def stack_auth_request(method, endpoint, **kwargs): - res = requests.request( +_session = requests.Session() +_session.mount("https://", HTTPAdapter(max_retries=Retry( + total=3, backoff_factor=0.5, status_forcelist=(429, 500, 502, 503, 504) +))) + +def stack_auth_request(method, endpoint, **kwargs): + timeout = kwargs.pop("timeout", 10) + res = _session.request( method, f'https://api.stack-auth.com/{endpoint}', headers={ 'x-stack-access-type': 'server', 'x-stack-project-id': stack_project_id, 'x-stack-publishable-client-key': stack_publishable_client_key, 'x-stack-secret-server-key': stack_secret_server_key, **kwargs.pop('headers', {}), }, - timeout=10, + timeout=timeout, **kwargs, )Also applies to: 303-316
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
docs/templates-python/concepts/backend-integration.mdx
(1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/templates-python/concepts/backend-integration.mdx
[grammar] ~448-~448: There might be a mistake here.
Context: ...d based on your endpoint's requirements: - Use JWT for high-performance endpoin...
(QB_NEW_EN)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: setup-tests
- GitHub Check: docker
- GitHub Check: all-good
- GitHub Check: docker
- GitHub Check: lint_and_build (latest)
- GitHub Check: build (22.x)
- GitHub Check: build (22.x)
- GitHub Check: restart-dev-and-test
- GitHub Check: Security Check
🔇 Additional comments (1)
docs/templates-python/concepts/backend-integration.mdx (1)
1-24
: Overall: strong addition.Clear flow, runnable snippets across Flask/FastAPI/Django, and good guidance on JWT vs REST tradeoffs.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (3)
docs/templates-python/concepts/backend-integration.mdx (3)
201-204
: Normalize header casing for consistency.Use the same header style across docs (case-insensitive, but consistency helps). This was flagged earlier too.
- user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ - 'x-stack-access-token': access_token - }) + user_data = stack_auth_request('GET', 'api/v1/users/me', headers={ + 'X-Stack-Access-Token': access_token + })
57-63
: Add issuer validation and require core claims in jwt.decode (security).Without issuer checks and required claims, tokens from unintended issuers or missing critical claims may be accepted.
Apply:
payload = jwt.decode( access_token, signing_key.key, algorithms=["ES256"], - audience="<your-project-id>", - + audience="<your-project-id>", + issuer="https://api.stack-auth.com/api/v1/projects/<your-project-id>", + options={"require": ["exp", "iat", "iss", "aud", "sub"]}, + leeway=30, )
331-336
: Replicate issuer/claim enforcement in the complete example.Keep security posture consistent across snippets.
payload = jwt.decode( access_token, signing_key.key, algorithms=["ES256"], - audience=stack_project_id + audience=stack_project_id, + issuer=f"https://api.stack-auth.com/api/v1/projects/{stack_project_id}", + options={"require": ["exp", "iat", "iss", "aud", "sub"]}, + leeway=30, )
🧹 Nitpick comments (3)
docs/templates-python/concepts/backend-integration.mdx (3)
131-137
: FastAPI: set explicit header alias to match documented header name.Prevents confusion and ensures the parameter binds to the exact header spelling shown elsewhere.
-async def get_current_user(x_stack_access_token: Optional[str] = Header(None)): +async def get_current_user( + x_stack_access_token: Optional[str] = Header(None, alias="X-Stack-Access-Token") +):
298-305
: Fail fast if required server credentials are missing.You check STACK_PROJECT_ID; also validate the keys before first API call.
stack_publishable_client_key = os.getenv("STACK_PUBLISHABLE_CLIENT_KEY") stack_secret_server_key = os.getenv("STACK_SECRET_SERVER_KEY") if not stack_project_id: raise RuntimeError("STACK_PROJECT_ID is not set") + +if not stack_publishable_client_key: + raise RuntimeError("STACK_PUBLISHABLE_CLIENT_KEY is not set") +if not stack_secret_server_key: + raise RuntimeError("STACK_SECRET_SERVER_KEY is not set")
306-323
: Use a shared requests.Session for connection pooling.Improves throughput and reduces latency on REST calls, aligning with your “Connection Pooling” note.
Example (add near setup and use below):
import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry session = requests.Session() session.mount("https://", HTTPAdapter(max_retries=Retry(total=3, backoff_factor=0.3))))Then inside stack_auth_request:
- res = requests.request( + res = session.request( method, f'https://api.stack-auth.com/{endpoint}', headers={ ... }, timeout=10, **kwargs, )
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
docs/templates-python/concepts/backend-integration.mdx
(1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/templates-python/concepts/backend-integration.mdx
[grammar] ~448-~448: There might be a mistake here.
Context: ...d based on your endpoint's requirements: - Use JWT for high-performance endpoin...
(QB_NEW_EN)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: lint_and_build (latest)
- GitHub Check: build (22.x)
- GitHub Check: build (22.x)
- GitHub Check: setup-tests
- GitHub Check: restart-dev-and-test
- GitHub Check: docker
- GitHub Check: all-good
- GitHub Check: docker
- GitHub Check: Security Check
🔇 Additional comments (2)
docs/templates-python/concepts/backend-integration.mdx (2)
83-90
: Verify MDX Tabs components availability.Ensure Tabs/TabsList/TabsTrigger/TabsContent are globally provided by the docs runtime; otherwise import them.
If imports are needed, add the appropriate import at the top of the MDX file per your docs framework conventions.
192-199
: Relative link is valid
The path../getting-started/setup
correctly points todocs/templates-python/getting-started/setup.mdx
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's much more Python stuff we could do, but this should do the trick for now!
… templates, and added new document to the docs-platform.yml <!-- Make sure you've read the CONTRIBUTING.md guidelines: https://github.com/stack-auth/stack-auth/blob/dev/CONTRIBUTING.md --> Adds Python Backend Integration docs <!-- ELLIPSIS_HIDDEN --> ---- > [!IMPORTANT] > Add Python backend integration documentation for Stack Auth, detailing JWT and REST API methods with examples. > > - **Documentation**: > - Added `backend-integration.mdx` to provide a guide for integrating Stack Auth into Python backends. > - Describes token flow, JWT verification, and REST API verification methods. > - Includes examples for Flask, FastAPI, and Django frameworks. > - Covers environment setup, error handling, and performance considerations. > - **Navigation**: > - Updated `meta.json` to include `concepts/backend-integration` in the documentation structure. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=stack-auth%2Fstack-auth&utm_source=github&utm_medium=referral)<sup> for 0fa0071. You can [customize](https://app.ellipsis.dev/stack-auth/settings/summaries) this summary. It will automatically update as commits are pushed.</sup> ---- <!-- ELLIPSIS_HIDDEN --> <!-- RECURSEML_SUMMARY:START --> ## Review by RecurseML _🔍 Review performed on [a77d50c..dd2c3c7](stack-auth/stack-auth@a77d50c...dd2c3c77a29958c259b706a44437063a6155a21b)_ ✨ No bugs found, your code is sparkling clean <details> <summary>⏭️ Files skipped (low suspicion) (3)</summary> • `docs/docs-platform.yml` • `docs/templates-python/concepts/backend-integration.mdx` • `docs/templates-python/meta.json` </details> [](https://discord.gg/n3SsVDAW6U) <!-- RECURSEML_SUMMARY:END --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - Documentation - Added a comprehensive guide for integrating Stack Auth into Python backends. - Describes the token flow (client obtains access token and sends it via X-Stack-Access-Token). - Details two approaches: local JWT verification and server-side REST verification. - Includes framework examples for Flask, FastAPI, and Django with auth enforcement patterns. - Covers environment setup, error handling patterns, and performance/caching recommendations. - Updated navigation to include the new Backend Integration page under Concepts. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Konsti Wohlwend <n2d4xc@gmail.com>
… templates, and added new document to the docs-platform.yml
Adds Python Backend Integration docs
Important
Add Python backend integration documentation for Stack Auth, detailing JWT and REST API methods with examples.
backend-integration.mdx
to provide a guide for integrating Stack Auth into Python backends.meta.json
to includeconcepts/backend-integration
in the documentation structure.This description was created by
for 0fa0071. You can customize this summary. It will automatically update as commits are pushed.
Review by RecurseML
🔍 Review performed on a77d50c..dd2c3c7
✨ No bugs found, your code is sparkling clean
⏭️ Files skipped (low suspicion) (3)
•
docs/docs-platform.yml
•
docs/templates-python/concepts/backend-integration.mdx
•
docs/templates-python/meta.json
Summary by CodeRabbit