Compare commits

..

2 Commits

Author SHA1 Message Date
38e5a94701 Added cognito authentication - Fix 4
All checks were successful
AWS Deploy on Push / build (push) Successful in 1m11s
2025-05-15 16:12:49 -05:00
7b7ff78030 Added cognito authentication - Fix 3 2025-05-15 16:11:30 -05:00
4 changed files with 25 additions and 13 deletions

View File

@@ -14,6 +14,7 @@
"iptv",
"nohup",
"passlib",
"pyjwt",
"starlette",
"stefano",
"uvicorn",

View File

@@ -1,16 +1,16 @@
import os
import boto3
import requests
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2AuthorizationCodeBearer
from fastapi.responses import RedirectResponse
from typing import Optional
REGION = "us-east-2"
USER_POOL_ID = os.getenv("COGNITO_USER_POOL_ID")
CLIENT_ID = os.getenv("COGNITO_CLIENT_ID")
DOMAIN = f"https://iptv-updater.auth.{REGION}.amazoncognito.com"
REDIRECT_URI = "http://localhost:8000/auth/callback"
REDIRECT_URI = f"http://localhost:8000/auth/callback"
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl=f"{DOMAIN}/oauth2/authorize",
@@ -29,6 +29,7 @@ def exchange_code_for_token(code: str):
response = requests.post(token_url, data=data)
if response.status_code == 200:
return response.json()
print(f"Token exchange failed: {response.text}") # Add logging
raise HTTPException(status_code=400, detail="Failed to exchange code for token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
@@ -36,15 +37,25 @@ async def get_current_user(token: str = Depends(oauth2_scheme)):
return RedirectResponse(
f"{DOMAIN}/login?client_id={CLIENT_ID}"
f"&response_type=code"
f"&scope=openid"
f"&scope=openid+email+profile" # Added more scopes
f"&redirect_uri={REDIRECT_URI}"
)
try:
cognito = boto3.client('cognito-idp', region_name=REGION)
response = cognito.get_user(AccessToken=token)
return response
# Decode JWT token instead of using get_user
decoded = jwt.decode(
token,
options={"verify_signature": False} # We trust tokens from Cognito
)
return {
"Username": decoded.get("email") or decoded.get("sub"),
"UserAttributes": [
{"Name": k, "Value": v}
for k, v in decoded.items()
]
}
except Exception as e:
print(f"Token verification failed: {str(e)}") # Add logging
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",

View File

@@ -17,19 +17,18 @@ async def protected_route(user = Depends(get_current_user)):
@app.get("/auth/callback")
async def auth_callback(code: str):
try:
# Exchange the authorization code for tokens
tokens = exchange_code_for_token(code)
# Create a response with the access token
# Use id_token instead of access_token
response = JSONResponse(content={
"message": "Authentication successful",
"access_token": tokens["access_token"]
"id_token": tokens["id_token"] # Changed from access_token
})
# Set the access token as a cookie
# Store id_token in cookie
response.set_cookie(
key="access_token",
value=tokens["access_token"],
key="token",
value=tokens["id_token"], # Changed from access_token
httponly=True,
secure=True,
samesite="lax"

View File

@@ -7,4 +7,5 @@ uvicorn==0.22.0
requests==2.31.0
passlib[bcrypt]==1.7.4
boto3==1.28.0
starlette>=0.27.0
starlette>=0.27.0
pyjwt==2.7.0