-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add TwitterSSO to support Twitter (X) login (#139)
* feat: add TwitterSSO to support Twitter (X) login
- Loading branch information
1 parent
2857ab7
commit fd23647
Showing
21 changed files
with
347 additions
and
51 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
"""Twitter (X) Login Example | ||
""" | ||
|
||
import os | ||
import uvicorn | ||
from fastapi import FastAPI, Request | ||
from fastapi_sso.sso.twitter import TwitterSSO | ||
|
||
CLIENT_ID = os.environ["CLIENT_ID"] | ||
CLIENT_SECRET = os.environ["CLIENT_SECRET"] | ||
|
||
app = FastAPI() | ||
|
||
sso = TwitterSSO( | ||
client_id=CLIENT_ID, | ||
client_secret=CLIENT_SECRET, | ||
redirect_uri="http://127.0.0.1:5000/auth/callback", | ||
allow_insecure_http=True, | ||
) | ||
|
||
|
||
@app.get("/auth/login") | ||
async def auth_init(): | ||
"""Initialize auth and redirect""" | ||
with sso: | ||
return await sso.get_login_redirect() | ||
|
||
|
||
@app.get("/auth/callback") | ||
async def auth_callback(request: Request): | ||
"""Verify login""" | ||
with sso: | ||
user = await sso.verify_and_process(request) | ||
return user | ||
|
||
|
||
if __name__ == "__main__": | ||
uvicorn.run(app="examples.twitter:app", host="127.0.0.1", port=5000) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
"""PKCE-related helper functions""" | ||
|
||
import base64 | ||
import hashlib | ||
import os | ||
from typing import Tuple | ||
|
||
|
||
def get_code_verifier(length: int = 96) -> str: | ||
"""Get code verifier for PKCE challenge""" | ||
length = max(43, min(length, 128)) | ||
bytes_length = int(length * 3 / 4) | ||
return base64.urlsafe_b64encode(os.urandom(bytes_length)).decode("utf-8").replace("=", "")[:length] | ||
|
||
|
||
def get_pkce_challenge_pair(verifier_length: int = 96) -> Tuple[str, str]: | ||
"""Get tuple of (verifier, challenge) for PKCE challenge.""" | ||
code_verifier = get_code_verifier(verifier_length) | ||
code_challenge = ( | ||
base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("utf-8")).digest()) | ||
.decode("utf-8") | ||
.replace("=", "") | ||
) | ||
|
||
return (code_verifier, code_challenge) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
"""Twitter (X) SSO Oauth Helper class""" | ||
|
||
from typing import TYPE_CHECKING, Optional | ||
|
||
from fastapi_sso.sso.base import DiscoveryDocument, OpenID, SSOBase | ||
|
||
if TYPE_CHECKING: | ||
import httpx # pragma: no cover | ||
|
||
|
||
class TwitterSSO(SSOBase): | ||
"""Class providing login via Twitter SSO""" | ||
|
||
provider = "twitter" | ||
scope = ["users.read", "tweet.read"] | ||
uses_pkce = True | ||
requires_state = True | ||
|
||
async def get_discovery_document(self) -> DiscoveryDocument: | ||
return { | ||
"authorization_endpoint": "https://twitter.com/i/oauth2/authorize", | ||
"token_endpoint": "https://api.twitter.com/2/oauth2/token", | ||
"userinfo_endpoint": "https://api.twitter.com/2/users/me", | ||
} | ||
|
||
async def openid_from_response(self, response: dict, session: Optional["httpx.AsyncClient"] = None) -> OpenID: | ||
first_name, *last_name_parts = response["data"].get("name", "").split(" ") | ||
last_name = " ".join(last_name_parts) if last_name_parts else None | ||
return OpenID( | ||
id=str(response["data"]["id"]), | ||
display_name=response["data"]["username"], | ||
first_name=first_name, | ||
last_name=last_name, | ||
provider=self.provider, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
"""Helper functions to generate state param""" | ||
|
||
import base64 | ||
import os | ||
|
||
|
||
def generate_random_state(length: int = 64) -> str: | ||
"""Generate a url-safe string to use as a state""" | ||
bytes_length = int(length * 3 / 4) | ||
return base64.urlsafe_b64encode(os.urandom(bytes_length)).decode("utf-8") |
Oops, something went wrong.