Skip to content

Instantly share code, notes, and snippets.

@TheOnlyWayUp
Created September 3, 2023 15:06
Show Gist options
  • Save TheOnlyWayUp/99feb390bf4c83988061a834b12d5c3d to your computer and use it in GitHub Desktop.
Save TheOnlyWayUp/99feb390bf4c83988061a834b12d5c3d to your computer and use it in GitHub Desktop.
Microsoft OAuth Python

Code example for flow present in docs.

Leverages FastAPI, but not required. I had a tough time understanding the docs, I thought they meant query params lol (to retrieve the access token).

Anyway, I've made this gist to help you guys out, maybe save a few minutes.

TheOnlyWayUp © 2023

"""Authentication Handler for Microsoft Teams."""
from typing import Optional
from fastapi import APIRouter
from fastapi.responses import RedirectResponse
from rich import print
import aiohttp
router = APIRouter(prefix="/auth", tags=["auth"])
@router.get("/")
async def home(code: Optional[str] = None):
if not code:
return RedirectResponse(
"""https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}&response_mode=query&scope={scopes}"""
)
async with aiohttp.ClientSession() as session:
async with session.post(
f"""https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token?scope={scopes}""",
data={
"grant_type": "authorization_code",
"code": code,
"client_id": "{client_id}",
"redirect_uri": "{redirect_uri}",
"client_secret": "{client_secret}",
},
) as response:
data = await response.json() # Keys: token_type, bearer, scope, expires_in, ext_expires_in, access_token,
# 🙏
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment