O365 - Microsoft Graph and Office 365 API made easy
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Central authentication system for Microsoft 365 services supporting multiple OAuth flows, automatic token refresh, and flexible token storage backends.
Create an account instance with client credentials and optional configuration for specific authentication flows and resource access.
class Account:
def __init__(self, credentials: tuple[str, str], *,
username: str = None,
protocol: Protocol = None,
main_resource: str = None,
auth_flow_type: str = 'authorization',
tenant_id: str = 'common',
**kwargs):
"""
Create an Account instance for Microsoft 365 services.
Parameters:
- credentials: tuple of (client_id, client_secret)
- username: username for this account (optional)
- protocol: Protocol instance (defaults to MSGraphProtocol)
- main_resource: main resource identifier ('me', 'users/{id}', etc.)
- auth_flow_type: 'authorization', 'credentials', 'password', or 'public'
- tenant_id: Azure AD tenant ID (defaults to 'common')
"""Perform OAuth authentication with Microsoft's identity platform supporting different grant types and scopes.
def authenticate(self, *, requested_scopes: list[str] = None, **kwargs) -> bool:
"""
Authenticate the account with Microsoft 365.
Parameters:
- requested_scopes: list of permission scopes to request
Returns:
- bool: True if authentication successful
"""
def is_authenticated(self) -> bool:
"""
Check if the account is currently authenticated.
Returns:
- bool: True if valid authentication exists
"""
def clear_token_cache(self) -> None:
"""Clear all cached authentication tokens."""Retrieve information about the authenticated user and manage user context.
def get_current_user(self) -> User:
"""
Get the current authenticated user.
Returns:
- User: Current user object with profile information
"""
def new_user(self, user_id: str) -> User:
"""
Create a User instance for a specific user.
Parameters:
- user_id: User identifier or email address
Returns:
- User: User object for the specified user
"""Manage OAuth token storage with various backend options for different deployment scenarios.
# Available token backends
class FileSystemTokenBackend:
def __init__(self, token_path: str = None, token_filename: str = 'o365_token.txt'): ...
class EnvTokenBackend:
def __init__(self, env_var_name: str = 'O365_TOKEN'): ...
class AWSS3Backend:
def __init__(self, bucket_name: str, object_key: str, **aws_kwargs): ...
class FirestoreBackend:
def __init__(self, collection_name: str = 'tokens', document_id: str = None): ...
class AWSSecretsBackend:
def __init__(self, secret_name: str, **aws_kwargs): ...
class BitwardenSecretsManagerBackend:
def __init__(self, secret_id: str, access_token: str = None): ...
class DjangoTokenBackend:
def __init__(self, user_model, token_field: str = 'o365_token'): ...Low-level connection and protocol management for advanced use cases.
class Connection:
def __init__(self, credentials: tuple[str, str], **kwargs): ...
def get_session(self) -> requests.Session:
"""Get the requests session with authentication headers."""
def refresh_token(self) -> bool:
"""Refresh the OAuth access token."""
class MSGraphProtocol(Protocol):
def __init__(self, api_version: str = 'v1.0', **kwargs): ...
@property
def graph_url(self) -> str:
"""Base Microsoft Graph API URL."""Authentication-related exceptions and error handling patterns.
# Common authentication errors
class AuthenticationError(Exception):
"""Raised when authentication fails."""
class TokenExpiredError(AuthenticationError):
"""Raised when token has expired and refresh failed."""
class InvalidCredentialsError(AuthenticationError):
"""Raised when provided credentials are invalid."""from O365 import Account
# Setup with client credentials
credentials = ('your_client_id', 'your_client_secret')
account = Account(credentials)
# Authenticate with required scopes
scopes = ['Mail.Read', 'Calendar.Read', 'Files.Read']
if account.authenticate(scopes=scopes):
print('Authentication successful!')
user = account.get_current_user()
print(f'Authenticated as: {user.display_name}')
else:
print('Authentication failed')from O365 import Account, AWSS3Backend
# Use AWS S3 for token storage
token_backend = AWSS3Backend(
bucket_name='my-tokens-bucket',
object_key='o365-tokens/app-token.json'
)
credentials = ('client_id', 'client_secret')
account = Account(credentials, token_backend=token_backend)from O365 import Account
# Application-only authentication (no user)
credentials = ('client_id', 'client_secret')
account = Account(
credentials,
auth_flow_type='credentials',
tenant_id='your-tenant-id'
)
if account.authenticate():
# Access application-level resources
directory = account.directory()
users = directory.get_users()Install with Tessl CLI
npx tessl i tessl/pypi-o365