148 lines
No EOL
6 KiB
Python
148 lines
No EOL
6 KiB
Python
import requests
|
|
import jwt
|
|
from jwt import PyJWKClient
|
|
import logging
|
|
from typing import Optional, Dict, Any
|
|
from flask import current_app
|
|
|
|
class MSALService:
|
|
"""Service for validating Microsoft MSAL tokens and extracting user information."""
|
|
|
|
def __init__(self):
|
|
self.tenant_id = 'e519c2e6-bc6d-4fdf-8d9c-923c2f002385'
|
|
self.client_id = '7e9b250a-d984-4fba-8e1c-a0622242a595'
|
|
|
|
# Microsoft endpoints
|
|
self.jwks_url = f'https://login.microsoftonline.com/{self.tenant_id}/discovery/v2.0/keys'
|
|
self.graph_me_url = 'https://graph.microsoft.com/v1.0/me'
|
|
|
|
# Initialize JWK client for token verification
|
|
self.jwks_client = PyJWKClient(self.jwks_url)
|
|
|
|
def validate_token(self, access_token: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Validate a Microsoft access token and return user information.
|
|
|
|
Args:
|
|
access_token: The Microsoft access token to validate
|
|
|
|
Returns:
|
|
Dictionary containing user information if valid, None if invalid
|
|
"""
|
|
try:
|
|
# First, try to get user info from Microsoft Graph API
|
|
user_info = self._get_user_info_from_graph(access_token)
|
|
if user_info:
|
|
return user_info
|
|
|
|
# If Graph API fails, try to decode the JWT token directly
|
|
return self._decode_jwt_token(access_token)
|
|
|
|
except Exception as e:
|
|
current_app.logger.error(f"Token validation failed: {str(e)}")
|
|
return None
|
|
|
|
def _get_user_info_from_graph(self, access_token: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Get user information from Microsoft Graph API.
|
|
|
|
Args:
|
|
access_token: The Microsoft access token
|
|
|
|
Returns:
|
|
Dictionary containing user information if successful, None if failed
|
|
"""
|
|
try:
|
|
headers = {
|
|
'Authorization': f'Bearer {access_token}',
|
|
'Content-Type': 'application/json'
|
|
}
|
|
|
|
response = requests.get(self.graph_me_url, headers=headers, timeout=10)
|
|
|
|
if response.status_code == 200:
|
|
user_data = response.json()
|
|
|
|
return {
|
|
'microsoft_id': user_data.get('id'),
|
|
'username': user_data.get('userPrincipalName', '').split('@')[0],
|
|
'email': user_data.get('mail') or user_data.get('userPrincipalName'),
|
|
'display_name': user_data.get('displayName', ''),
|
|
'given_name': user_data.get('givenName', ''),
|
|
'surname': user_data.get('surname', ''),
|
|
'auth_type': 'microsoft'
|
|
}
|
|
else:
|
|
current_app.logger.warning(f"Graph API request failed with status {response.status_code}: {response.text}")
|
|
return None
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
current_app.logger.error(f"Graph API request failed: {str(e)}")
|
|
return None
|
|
|
|
def _decode_jwt_token(self, access_token: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Decode and validate JWT token directly.
|
|
|
|
Args:
|
|
access_token: The Microsoft access token (JWT)
|
|
|
|
Returns:
|
|
Dictionary containing user information if valid, None if invalid
|
|
"""
|
|
try:
|
|
# Get the signing key
|
|
signing_key = self.jwks_client.get_signing_key_from_jwt(access_token)
|
|
|
|
# Decode and validate the token
|
|
decoded_token = jwt.decode(
|
|
access_token,
|
|
signing_key.key,
|
|
algorithms=['RS256'],
|
|
audience=self.client_id,
|
|
issuer=f'https://login.microsoftonline.com/{self.tenant_id}/v2.0'
|
|
)
|
|
|
|
# Extract user information from token claims
|
|
return {
|
|
'microsoft_id': decoded_token.get('oid') or decoded_token.get('sub'),
|
|
'username': decoded_token.get('preferred_username', '').split('@')[0],
|
|
'email': decoded_token.get('email') or decoded_token.get('preferred_username'),
|
|
'display_name': decoded_token.get('name', ''),
|
|
'given_name': decoded_token.get('given_name', ''),
|
|
'surname': decoded_token.get('family_name', ''),
|
|
'auth_type': 'microsoft'
|
|
}
|
|
|
|
except jwt.InvalidTokenError as e:
|
|
current_app.logger.error(f"JWT token validation failed: {str(e)}")
|
|
return None
|
|
except Exception as e:
|
|
current_app.logger.error(f"Token decoding failed: {str(e)}")
|
|
return None
|
|
|
|
def create_user_data(self, microsoft_user_info: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""
|
|
Create user data dictionary from Microsoft user information.
|
|
|
|
Args:
|
|
microsoft_user_info: User information from Microsoft
|
|
|
|
Returns:
|
|
Dictionary formatted for our user system
|
|
"""
|
|
# Use display name if available, otherwise construct from given/surname
|
|
display_name = microsoft_user_info.get('display_name', '')
|
|
if not display_name:
|
|
given_name = microsoft_user_info.get('given_name', '')
|
|
surname = microsoft_user_info.get('surname', '')
|
|
display_name = f"{given_name} {surname}".strip() or microsoft_user_info.get('username', 'Microsoft User')
|
|
|
|
return {
|
|
'username': display_name, # Use display name as username for Microsoft users
|
|
'email': microsoft_user_info.get('email', ''),
|
|
'microsoft_id': microsoft_user_info.get('microsoft_id', ''),
|
|
'role': 'user', # Default role for all users
|
|
'auth_type': 'microsoft',
|
|
'password_hash': None # Microsoft users don't have local passwords
|
|
} |