Browse Source

Feat: Add OAuth `state` parameter for CSRF protection (#7709)

### What problem does this PR solve?

Add OAuth `state` parameter for CSRF protection:
- Updated `get_authorization_url()` to accept an optional state
parameter
- Generated a unique state value during OAuth login and stored in
session
- Verified state parameter in callback to ensure request legitimacy

This PR follows OAuth 2.0 security best practices by ensuring that the
authorization request originates from the same user who initiated the
flow.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
tags/v0.19.0
Chaoxi Weng 5 months ago
parent
commit
6ed81d6774
No account linked to committer's email address
2 changed files with 12 additions and 2 deletions
  1. 3
    1
      api/apps/auth/oauth.py
  2. 9
    1
      api/apps/user_app.py

+ 3
- 1
api/apps/auth/oauth.py View File

self.http_request_timeout = 7 self.http_request_timeout = 7




def get_authorization_url(self):
def get_authorization_url(self, state=None):
""" """
Generate the authorization URL for user login. Generate the authorization URL for user login.
""" """
} }
if self.scope: if self.scope:
params["scope"] = self.scope params["scope"] = self.scope
if state:
params["state"] = state
authorization_url = f"{self.authorization_url}?{urllib.parse.urlencode(params)}" authorization_url = f"{self.authorization_url}?{urllib.parse.urlencode(params)}"
return authorization_url return authorization_url



+ 9
- 1
api/apps/user_app.py View File

raise ValueError(f"Invalid channel name: {channel}") raise ValueError(f"Invalid channel name: {channel}")
auth_cli = get_auth_client(channel_config) auth_cli = get_auth_client(channel_config)


auth_url = auth_cli.get_authorization_url()
state = get_uuid()
session["oauth_state"] = state
auth_url = auth_cli.get_authorization_url(state)
return redirect(auth_url) return redirect(auth_url)




raise ValueError(f"Invalid channel name: {channel}") raise ValueError(f"Invalid channel name: {channel}")
auth_cli = get_auth_client(channel_config) auth_cli = get_auth_client(channel_config)


# Check the state
state = request.args.get("state")
if not state or state != session.get("oauth_state"):
return redirect("/?error=invalid_state")
session.pop("oauth_state", None)

# Obtain the authorization code # Obtain the authorization code
code = request.args.get("code") code = request.args.get("code")
if not code: if not code:

Loading…
Cancel
Save