0
# Authentication and Account Management
1
2
Central authentication system for Microsoft 365 services supporting multiple OAuth flows, automatic token refresh, and flexible token storage backends.
3
4
## Capabilities
5
6
### Account Creation and Setup
7
8
Create an account instance with client credentials and optional configuration for specific authentication flows and resource access.
9
10
```python { .api }
11
class Account:
12
def __init__(self, credentials: tuple[str, str], *,
13
username: str = None,
14
protocol: Protocol = None,
15
main_resource: str = None,
16
auth_flow_type: str = 'authorization',
17
tenant_id: str = 'common',
18
**kwargs):
19
"""
20
Create an Account instance for Microsoft 365 services.
21
22
Parameters:
23
- credentials: tuple of (client_id, client_secret)
24
- username: username for this account (optional)
25
- protocol: Protocol instance (defaults to MSGraphProtocol)
26
- main_resource: main resource identifier ('me', 'users/{id}', etc.)
27
- auth_flow_type: 'authorization', 'credentials', 'password', or 'public'
28
- tenant_id: Azure AD tenant ID (defaults to 'common')
29
"""
30
```
31
32
### Authentication Flow
33
34
Perform OAuth authentication with Microsoft's identity platform supporting different grant types and scopes.
35
36
```python { .api }
37
def authenticate(self, *, requested_scopes: list[str] = None, **kwargs) -> bool:
38
"""
39
Authenticate the account with Microsoft 365.
40
41
Parameters:
42
- requested_scopes: list of permission scopes to request
43
44
Returns:
45
- bool: True if authentication successful
46
"""
47
48
def is_authenticated(self) -> bool:
49
"""
50
Check if the account is currently authenticated.
51
52
Returns:
53
- bool: True if valid authentication exists
54
"""
55
56
def clear_token_cache(self) -> None:
57
"""Clear all cached authentication tokens."""
58
```
59
60
### User Information
61
62
Retrieve information about the authenticated user and manage user context.
63
64
```python { .api }
65
def get_current_user(self) -> User:
66
"""
67
Get the current authenticated user.
68
69
Returns:
70
- User: Current user object with profile information
71
"""
72
73
def new_user(self, user_id: str) -> User:
74
"""
75
Create a User instance for a specific user.
76
77
Parameters:
78
- user_id: User identifier or email address
79
80
Returns:
81
- User: User object for the specified user
82
"""
83
```
84
85
### Token Backend Management
86
87
Manage OAuth token storage with various backend options for different deployment scenarios.
88
89
```python { .api }
90
# Available token backends
91
class FileSystemTokenBackend:
92
def __init__(self, token_path: str = None, token_filename: str = 'o365_token.txt'): ...
93
94
class EnvTokenBackend:
95
def __init__(self, env_var_name: str = 'O365_TOKEN'): ...
96
97
class AWSS3Backend:
98
def __init__(self, bucket_name: str, object_key: str, **aws_kwargs): ...
99
100
class FirestoreBackend:
101
def __init__(self, collection_name: str = 'tokens', document_id: str = None): ...
102
103
class AWSSecretsBackend:
104
def __init__(self, secret_name: str, **aws_kwargs): ...
105
106
class BitwardenSecretsManagerBackend:
107
def __init__(self, secret_id: str, access_token: str = None): ...
108
109
class DjangoTokenBackend:
110
def __init__(self, user_model, token_field: str = 'o365_token'): ...
111
```
112
113
### Connection Management
114
115
Low-level connection and protocol management for advanced use cases.
116
117
```python { .api }
118
class Connection:
119
def __init__(self, credentials: tuple[str, str], **kwargs): ...
120
121
def get_session(self) -> requests.Session:
122
"""Get the requests session with authentication headers."""
123
124
def refresh_token(self) -> bool:
125
"""Refresh the OAuth access token."""
126
127
class MSGraphProtocol(Protocol):
128
def __init__(self, api_version: str = 'v1.0', **kwargs): ...
129
130
@property
131
def graph_url(self) -> str:
132
"""Base Microsoft Graph API URL."""
133
```
134
135
### Error Handling
136
137
Authentication-related exceptions and error handling patterns.
138
139
```python { .api }
140
# Common authentication errors
141
class AuthenticationError(Exception):
142
"""Raised when authentication fails."""
143
144
class TokenExpiredError(AuthenticationError):
145
"""Raised when token has expired and refresh failed."""
146
147
class InvalidCredentialsError(AuthenticationError):
148
"""Raised when provided credentials are invalid."""
149
```
150
151
## Usage Examples
152
153
### Basic Authentication
154
155
```python
156
from O365 import Account
157
158
# Setup with client credentials
159
credentials = ('your_client_id', 'your_client_secret')
160
account = Account(credentials)
161
162
# Authenticate with required scopes
163
scopes = ['Mail.Read', 'Calendar.Read', 'Files.Read']
164
if account.authenticate(scopes=scopes):
165
print('Authentication successful!')
166
user = account.get_current_user()
167
print(f'Authenticated as: {user.display_name}')
168
else:
169
print('Authentication failed')
170
```
171
172
### Custom Token Backend
173
174
```python
175
from O365 import Account, AWSS3Backend
176
177
# Use AWS S3 for token storage
178
token_backend = AWSS3Backend(
179
bucket_name='my-tokens-bucket',
180
object_key='o365-tokens/app-token.json'
181
)
182
183
credentials = ('client_id', 'client_secret')
184
account = Account(credentials, token_backend=token_backend)
185
```
186
187
### Client Credentials Flow
188
189
```python
190
from O365 import Account
191
192
# Application-only authentication (no user)
193
credentials = ('client_id', 'client_secret')
194
account = Account(
195
credentials,
196
auth_flow_type='credentials',
197
tenant_id='your-tenant-id'
198
)
199
200
if account.authenticate():
201
# Access application-level resources
202
directory = account.directory()
203
users = directory.get_users()
204
```