or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

accounts.mdauthentication.mdindex.mdsearch.mdstatuses.mdstreaming.md

authentication.mddocs/

0

# Authentication & Setup

1

2

Complete OAuth authentication flows, application registration, and API client configuration for connecting to Mastodon instances. Handles credential persistence, token management, and various authentication scenarios.

3

4

## Capabilities

5

6

### Application Registration

7

8

Register a new application with a Mastodon instance to obtain client credentials required for OAuth authentication.

9

10

```python { .api }

11

@staticmethod

12

def create_app(

13

client_name: str,

14

scopes: list = None,

15

redirect_uris: str = "urn:ietf:wg:oauth:2.0:oob",

16

website: str = None,

17

to_file: str = None,

18

api_base_url: str = None,

19

request_timeout: int = 300,

20

session: requests.Session = None

21

) -> tuple:

22

"""

23

Register a new application with a Mastodon instance.

24

25

Args:

26

client_name: Name of the application

27

scopes: List of requested permissions (default: ['read', 'write', 'follow', 'push'])

28

redirect_uris: OAuth redirect URI for authorization flow

29

website: URL of application website (optional)

30

to_file: File path to save client credentials (optional)

31

api_base_url: Base URL of Mastodon instance (required)

32

request_timeout: HTTP request timeout in seconds

33

session: Custom requests session (optional)

34

35

Returns:

36

Tuple of (client_id, client_secret) or path to saved file

37

"""

38

```

39

40

### Client Initialization

41

42

Initialize the Mastodon API client with authentication credentials and configuration options.

43

44

```python { .api }

45

def __init__(

46

self,

47

client_id: str = None,

48

client_secret: str = None,

49

access_token: str = None,

50

api_base_url: str = None,

51

client_credential_file: str = None,

52

access_token_file: str = None,

53

debug_requests: bool = False,

54

ratelimit_method: str = "wait",

55

ratelimit_pacefactor: float = 1.1,

56

request_timeout: int = 300,

57

mastodon_version: str = None,

58

version_check_mode: str = "created",

59

session: requests.Session = None,

60

feature_set: str = "mainline",

61

user_agent: str = None,

62

lang: str = None

63

):

64

"""

65

Initialize Mastodon API client.

66

67

Args:

68

client_id: Application client ID

69

client_secret: Application client secret

70

access_token: User access token for authenticated requests

71

api_base_url: Base URL of Mastodon instance (e.g., 'https://mastodon.social')

72

client_credential_file: Path to file containing client credentials

73

access_token_file: Path to file containing access token

74

debug_requests: Enable request debugging output

75

ratelimit_method: Rate limit handling ('wait', 'throw', or 'pace')

76

ratelimit_pacefactor: Factor for rate limit pacing

77

request_timeout: HTTP request timeout in seconds

78

mastodon_version: Target Mastodon version for compatibility

79

version_check_mode: Version checking behavior ('created', 'changed', or 'none')

80

session: Custom requests session

81

feature_set: Feature set compatibility ('mainline', 'fedibird', 'pleroma')

82

user_agent: Custom user agent string

83

lang: Default language for requests

84

"""

85

```

86

87

### OAuth Authorization

88

89

Generate OAuth authorization URLs and handle the authorization flow for obtaining user access tokens.

90

91

```python { .api }

92

def auth_request_url(

93

self,

94

client_id: str = None,

95

redirect_uris: str = "urn:ietf:wg:oauth:2.0:oob",

96

scopes: list = None,

97

force_login: bool = False,

98

state: str = None

99

) -> str:

100

"""

101

Generate OAuth authorization URL for user authentication.

102

103

Args:

104

client_id: Application client ID (uses instance default if None)

105

redirect_uris: OAuth redirect URI

106

scopes: Requested permission scopes

107

force_login: Force user to log in even if already authenticated

108

state: Random state parameter for CSRF protection

109

110

Returns:

111

Authorization URL for user to visit

112

"""

113

114

def oauth_authorization_server_info(self) -> dict:

115

"""

116

Get OAuth authorization server metadata (Mastodon 4.3.0+).

117

118

Returns:

119

Dictionary containing OAuth server configuration

120

"""

121

122

def oauth_userinfo(self) -> dict:

123

"""

124

Get authenticated user information via OAuth userinfo endpoint (Mastodon 4.3.0+).

125

126

Returns:

127

Dictionary containing user profile information

128

"""

129

```

130

131

### User Authentication

132

133

Authenticate users and obtain access tokens using various authentication methods including username/password and authorization codes.

134

135

```python { .api }

136

def log_in(

137

self,

138

username: str = None,

139

password: str = None,

140

code: str = None,

141

redirect_uri: str = "urn:ietf:wg:oauth:2.0:oob",

142

refresh_token: str = None,

143

scopes: list = None,

144

to_file: str = None

145

) -> str:

146

"""

147

Authenticate user and obtain access token.

148

149

Args:

150

username: User's email or username (for password auth)

151

password: User's password (for password auth)

152

code: Authorization code from OAuth flow

153

redirect_uri: OAuth redirect URI (must match app registration)

154

refresh_token: Refresh token for token renewal

155

scopes: Requested permission scopes

156

to_file: File path to save access token

157

158

Returns:

159

Access token string

160

"""

161

```

162

163

### Credential Management

164

165

Manage, verify, and persist authentication credentials for seamless API access across sessions.

166

167

```python { .api }

168

def persistable_login_credentials(self) -> dict:

169

"""

170

Get current credentials in a format suitable for persistence.

171

172

Returns:

173

Dictionary containing client_id, client_secret, and access_token

174

"""

175

176

def revoke_access_token(self) -> bool:

177

"""

178

Revoke the current access token, invalidating it.

179

180

Returns:

181

True if token was successfully revoked

182

"""

183

184

def app_verify_credentials(self) -> dict:

185

"""

186

Verify application credentials and get app information.

187

188

Returns:

189

Dictionary containing application details

190

"""

191

```

192

193

### Cache Management

194

195

Clear internal caches and reset client state for troubleshooting and memory management.

196

197

```python { .api }

198

def clear_caches(self) -> None:

199

"""

200

Clear all internal caches (emoji cache, instance info, etc.).

201

"""

202

```

203

204

## Usage Examples

205

206

### Complete Authentication Flow

207

208

```python

209

from mastodon import Mastodon

210

211

# 1. Register application (do this once per application)

212

client_id, client_secret = Mastodon.create_app(

213

'My Bot Application',

214

api_base_url='https://mastodon.social',

215

to_file='clientcred.secret'

216

)

217

218

# 2. Create client instance

219

mastodon = Mastodon(

220

client_id=client_id,

221

client_secret=client_secret,

222

api_base_url='https://mastodon.social'

223

)

224

225

# 3. Get authorization URL for user

226

auth_url = mastodon.auth_request_url(scopes=['read', 'write'])

227

print(f"Visit this URL to authorize: {auth_url}")

228

229

# 4. User visits URL and gets authorization code

230

authorization_code = input("Enter authorization code: ")

231

232

# 5. Exchange code for access token

233

access_token = mastodon.log_in(

234

code=authorization_code,

235

to_file='usercred.secret'

236

)

237

238

# 6. Now you can make authenticated requests

239

user_info = mastodon.account_verify_credentials()

240

print(f"Logged in as: {user_info['acct']}")

241

```

242

243

### Using Saved Credentials

244

245

```python

246

from mastodon import Mastodon

247

248

# Load from credential files

249

mastodon = Mastodon(

250

client_credential_file='clientcred.secret',

251

access_token_file='usercred.secret',

252

api_base_url='https://mastodon.social'

253

)

254

255

# Verify credentials are still valid

256

try:

257

user_info = mastodon.account_verify_credentials()

258

print(f"Successfully authenticated as: {user_info['acct']}")

259

except Exception as e:

260

print(f"Authentication failed: {e}")

261

```

262

263

### Rate Limit Handling

264

265

```python

266

from mastodon import Mastodon

267

268

# Configure rate limiting behavior

269

mastodon = Mastodon(

270

access_token='your_token',

271

api_base_url='https://mastodon.social',

272

ratelimit_method='wait', # Wait when rate limited

273

ratelimit_pacefactor=1.1 # Slight delay to avoid limits

274

)

275

276

# Alternative: Handle rate limits manually

277

mastodon = Mastodon(

278

access_token='your_token',

279

api_base_url='https://mastodon.social',

280

ratelimit_method='throw' # Raise exception on rate limit

281

)

282

283

try:

284

timeline = mastodon.timeline_home()

285

except MastodonRatelimitError:

286

print("Rate limited! Wait before retrying.")

287

```

288

289

## Error Handling

290

291

Authentication operations can raise several specific exceptions:

292

293

```python

294

from mastodon import (

295

MastodonError, MastodonNetworkError, MastodonAPIError,

296

MastodonUnauthorizedError, MastodonRatelimitError

297

)

298

299

try:

300

mastodon = Mastodon(

301

access_token='invalid_token',

302

api_base_url='https://mastodon.social'

303

)

304

user_info = mastodon.account_verify_credentials()

305

except MastodonUnauthorizedError:

306

print("Invalid or expired access token")

307

except MastodonNetworkError:

308

print("Network connection failed")

309

except MastodonAPIError as e:

310

print(f"API error: {e}")

311

```

312

313

## Constants

314

315

```python { .api }

316

# Default OAuth scopes

317

_DEFAULT_SCOPES = ['read', 'write', 'follow', 'push']

318

319

# Available scope sets

320

_SCOPE_SETS = {

321

'read': ['read:accounts', 'read:blocks', 'read:bookmarks', ...],

322

'write': ['write:accounts', 'write:blocks', 'write:bookmarks', ...],

323

'follow': ['read:follows', 'write:follows'],

324

'push': ['push']

325

}

326

```