or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication-actions.mdauthentication-backends.mdexception-handling.mdindex.mdpipeline-system.mdstorage-models.mdstrategy-interface.mdutilities-helpers.md

authentication-backends.mddocs/

0

# Authentication Backends

1

2

Social Auth Core provides 195+ authentication backend implementations supporting OAuth 1.0/2.0, OpenID Connect, SAML, and custom authentication protocols. Each backend handles provider-specific authentication flows, token management, user data extraction, and API integration.

3

4

## Capabilities

5

6

### Base Authentication Backend

7

8

The foundation class that all authentication backends inherit from, providing the core authentication interface and common functionality.

9

10

```python { .api }

11

class BaseAuth:

12

"""

13

Base authentication backend class.

14

15

All authentication backends inherit from this class and implement

16

provider-specific authentication logic while maintaining a consistent interface.

17

"""

18

19

# Class attributes

20

name: str = "" # Provider name stored in database

21

supports_inactive_user: bool = False # Django auth compatibility

22

ID_KEY: str = "" # Key for extracting user ID from provider response

23

EXTRA_DATA: list | None = None # Additional data fields to store

24

GET_ALL_EXTRA_DATA: bool = False # Store all provider response data

25

REQUIRES_EMAIL_VALIDATION: bool = False # Email validation requirement

26

SEND_USER_AGENT: bool = False # Send User-Agent header

27

28

def __init__(self, strategy, redirect_uri=None):

29

"""

30

Initialize backend with strategy and redirect URI.

31

32

Parameters:

33

- strategy: Strategy instance for framework integration

34

- redirect_uri: Callback URL for OAuth flows (optional)

35

"""

36

37

def setting(self, name, default=None):

38

"""

39

Get setting value from strategy with backend-specific prefixing.

40

41

Parameters:

42

- name: Setting name

43

- default: Default value if setting not found

44

45

Returns:

46

Setting value or default

47

"""

48

49

def start(self):

50

"""

51

Start authentication flow.

52

53

Returns:

54

Redirect response to provider or HTML content

55

"""

56

57

def complete(self, *args, **kwargs):

58

"""

59

Complete authentication flow.

60

61

Returns:

62

Authenticated user instance

63

"""

64

65

def auth_url(self) -> str:

66

"""

67

Generate authentication URL for provider.

68

69

Returns:

70

URL string for redirecting user to provider

71

72

Raises:

73

NotImplementedError: Must be implemented by subclasses

74

"""

75

76

def auth_html(self) -> str:

77

"""

78

Generate authentication HTML for non-redirect flows.

79

80

Returns:

81

HTML string for authentication

82

"""

83

84

def auth_complete(self, *args, **kwargs):

85

"""

86

Handle provider callback and complete authentication.

87

88

Returns:

89

User data or authentication result

90

91

Raises:

92

NotImplementedError: Must be implemented by subclasses

93

"""

94

95

def authenticate(self, *args, **kwargs):

96

"""

97

Authenticate user using social credentials.

98

99

This method validates the backend matches the request and runs

100

the authentication pipeline to create or retrieve the user.

101

102

Parameters:

103

- backend: Backend instance (must match self.name)

104

- strategy: Strategy instance

105

- response: Provider response data

106

- Additional args/kwargs passed to pipeline

107

108

Returns:

109

Authenticated user instance or None

110

"""

111

112

def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):

113

"""

114

Run authentication pipeline.

115

116

Parameters:

117

- pipeline: List of pipeline function names

118

- pipeline_index: Starting index in pipeline

119

- Additional args/kwargs for pipeline functions

120

121

Returns:

122

User instance with social_user and is_new attributes

123

"""

124

125

def disconnect(self, *args, **kwargs):

126

"""

127

Disconnect social account from user.

128

129

Returns:

130

Dictionary with disconnection results

131

"""

132

133

def get_user_details(self, response):

134

"""

135

Extract user details from provider response.

136

137

Parameters:

138

- response: Provider response data

139

140

Returns:

141

Dictionary with user details (username, email, full_name, etc.)

142

143

Raises:

144

NotImplementedError: Must be implemented by subclasses

145

"""

146

147

def get_user_id(self, details, response):

148

"""

149

Extract user ID from provider response.

150

151

Parameters:

152

- details: User details dictionary

153

- response: Provider response data

154

155

Returns:

156

String user ID from provider

157

"""

158

159

def get_user(self, user_id):

160

"""

161

Get user instance by ID.

162

163

Parameters:

164

- user_id: User ID to lookup

165

166

Returns:

167

User instance or None

168

"""

169

170

def request(self, url, method="GET", *, headers=None, data=None, auth=None, params=None):

171

"""

172

Make HTTP request to provider API.

173

174

Parameters:

175

- url: Request URL

176

- method: HTTP method ("GET", "POST", "DELETE")

177

- headers: Request headers dictionary

178

- data: Request body data

179

- auth: Authentication credentials

180

- params: Query parameters

181

182

Returns:

183

HTTP response object

184

"""

185

186

def get_json(self, url, method="GET", *, headers=None, data=None, auth=None, params=None):

187

"""

188

Make HTTP request and parse JSON response.

189

190

Parameters:

191

- url: Request URL

192

- method: HTTP method

193

- headers: Request headers

194

- data: Request body

195

- auth: Authentication credentials

196

- params: Query parameters

197

198

Returns:

199

Parsed JSON response as dictionary

200

"""

201

```

202

203

### OAuth Base Classes

204

205

Base classes that provide OAuth-specific functionality for OAuth 1.0 and 2.0 authentication flows.

206

207

```python { .api }

208

class OAuthAuth(BaseAuth):

209

"""

210

Base OAuth authentication backend for OAuth 1.0 and 2.0 flows.

211

212

Provides common OAuth functionality including token management,

213

state validation, scope handling, and authorization URL generation.

214

"""

215

216

# OAuth-specific class attributes

217

AUTHORIZATION_URL: str = "" # Provider authorization endpoint

218

ACCESS_TOKEN_URL: str = "" # Provider token exchange endpoint

219

ACCESS_TOKEN_METHOD: str = "POST" # HTTP method for token requests

220

REVOKE_TOKEN_URL: str = "" # Token revocation endpoint

221

REVOKE_TOKEN_METHOD: str = "POST" # HTTP method for revocation

222

SCOPE_PARAMETER_NAME: str = "scope" # Parameter name for scope

223

DEFAULT_SCOPE: list = [] # Default OAuth scopes

224

SCOPE_SEPARATOR: str = " " # Scope separator in requests

225

REDIRECT_STATE: bool = True # Use state parameter for security

226

STATE_PARAMETER: str = "state" # State parameter name

227

228

def extra_data(self, user, uid, response, details=None, *args, **kwargs):

229

"""

230

Return extra user data from provider response.

231

232

Parameters:

233

- user: User instance

234

- uid: Provider user ID

235

- response: Provider response data

236

- details: User details dictionary

237

238

Returns:

239

Dictionary of extra data to store with social account

240

"""

241

242

def state_token(self):

243

"""

244

Generate state token for OAuth security.

245

246

Returns:

247

Random state token string

248

"""

249

250

def get_or_create_state(self):

251

"""

252

Get existing state from session or create new one.

253

254

Returns:

255

State token string or None

256

"""

257

258

def get_session_state(self):

259

"""

260

Get state from current session.

261

262

Returns:

263

State token from session

264

"""

265

266

def get_request_state(self):

267

"""

268

Get state from current request.

269

270

Returns:

271

State token from request parameters

272

"""

273

```

274

275

### OAuth 2.0 Backends

276

277

Popular OAuth 2.0 provider implementations for major social platforms and services.

278

279

```python { .api }

280

# Google OAuth 2.0

281

class GoogleOAuth2(BaseAuth):

282

"""Google OAuth 2.0 authentication backend."""

283

name = "google-oauth2"

284

285

# Facebook OAuth 2.0

286

class FacebookOAuth2(BaseAuth):

287

"""Facebook OAuth 2.0 authentication backend."""

288

name = "facebook"

289

290

# GitHub OAuth 2.0

291

class GithubOAuth2(BaseAuth):

292

"""GitHub OAuth 2.0 authentication backend."""

293

name = "github"

294

295

# Twitter OAuth 2.0 (new API)

296

class TwitterOAuth2(BaseAuth):

297

"""Twitter OAuth 2.0 authentication backend."""

298

name = "twitter-oauth2"

299

300

# LinkedIn OAuth 2.0

301

class LinkedinOAuth2(BaseAuth):

302

"""LinkedIn OAuth 2.0 authentication backend."""

303

name = "linkedin-oauth2"

304

305

# Microsoft Azure AD OAuth 2.0

306

class AzureADOAuth2(BaseAuth):

307

"""Azure AD OAuth 2.0 authentication backend."""

308

name = "azuread-oauth2"

309

310

# Apple OAuth 2.0

311

class AppleIdAuth(BaseAuth):

312

"""Apple Sign In authentication backend."""

313

name = "apple-id"

314

315

# Discord OAuth 2.0

316

class DiscordOAuth2(BaseAuth):

317

"""Discord OAuth 2.0 authentication backend."""

318

name = "discord"

319

320

# Slack OAuth 2.0

321

class SlackOAuth2(BaseAuth):

322

"""Slack OAuth 2.0 authentication backend."""

323

name = "slack-oauth2"

324

```

325

326

### OAuth 1.0 Backends

327

328

OAuth 1.0a implementations for providers that still use the older OAuth standard.

329

330

```python { .api }

331

# Twitter OAuth 1.0a (legacy API)

332

class TwitterOAuth(BaseAuth):

333

"""Twitter OAuth 1.0a authentication backend."""

334

name = "twitter"

335

336

# Flickr OAuth 1.0a

337

class FlickrOAuth(BaseAuth):

338

"""Flickr OAuth 1.0a authentication backend."""

339

name = "flickr"

340

```

341

342

### OpenID Connect Backends

343

344

OpenID Connect implementations for identity providers supporting the OIDC standard.

345

346

```python { .api }

347

class OpenIdConnectAuth(OAuthAuth):

348

"""

349

Generic OpenID Connect authentication backend.

350

351

Provides standards-compliant OIDC authentication with JWT token validation,

352

userinfo endpoint integration, and configurable OIDC discovery.

353

"""

354

name = "oidc"

355

356

# OIDC-specific constants

357

OIDC_ENDPOINT: str = "" # Base OIDC endpoint URL

358

ID_TOKEN_MAX_AGE: int = 600 # Maximum ID token age in seconds

359

DEFAULT_SCOPE: list = ["openid", "profile", "email"]

360

EXTRA_DATA: list = ["id_token", "refresh_token", "token_type"]

361

REDIRECT_STATE: bool = True

362

REVOKE_TOKEN_METHOD: str = "POST"

363

ID_KEY: str = "sub" # Subject claim from ID token

364

USERNAME_KEY: str = "preferred_username"

365

JWT_ALGORITHMS: list = ["RS256"] # Supported JWT algorithms

366

JWT_DECODE_OPTIONS: dict = {"verify_aud": True}

367

JWT_LEEWAY: int = 0 # Clock skew allowance in seconds

368

369

def __init__(self, *args, **kwargs):

370

"""

371

Initialize OIDC backend with configuration.

372

373

Loads OIDC configuration from settings including endpoints,

374

client credentials, and JWT validation parameters.

375

"""

376

377

def get_setting_config(self, setting_name, oidc_name, default):

378

"""

379

Get OIDC-specific setting with fallback hierarchy.

380

381

Parameters:

382

- setting_name: Base setting name

383

- oidc_name: OIDC provider name for namespaced settings

384

- default: Default value if setting not found

385

386

Returns:

387

Setting value with OIDC-specific overrides applied

388

"""

389

390

def authorization_url(self):

391

"""

392

Generate OIDC authorization URL.

393

394

Returns:

395

Complete authorization URL with OIDC parameters

396

"""

397

398

class Auth0(OpenIdConnectAuth):

399

"""Auth0 OpenID Connect authentication backend."""

400

name = "auth0"

401

```

402

403

### SAML Backends

404

405

SAML 2.0 implementation for enterprise single sign-on integration.

406

407

```python { .api }

408

class SAMLAuth(BaseAuth):

409

"""SAML 2.0 authentication backend."""

410

name = "saml"

411

412

def __init__(self, strategy, redirect_uri=None, idp=None):

413

"""

414

Initialize SAML backend.

415

416

Parameters:

417

- strategy: Strategy instance

418

- redirect_uri: Callback URL

419

- idp: Identity Provider configuration

420

"""

421

```

422

423

### Backend Utilities

424

425

Helper functions for backend discovery, loading, and management.

426

427

```python { .api }

428

def get_backend(backends, name):

429

"""

430

Get backend by name from backends list.

431

432

Parameters:

433

- backends: List of available backend classes

434

- name: Backend name to find

435

436

Returns:

437

Backend class or None if not found

438

"""

439

440

def load_backends(backend_names, strategy):

441

"""

442

Load backend instances from configuration.

443

444

Parameters:

445

- backend_names: List of backend names to load

446

- strategy: Strategy instance

447

448

Returns:

449

Dictionary mapping backend names to instances

450

"""

451

```

452

453

## Usage Examples

454

455

### Basic Backend Usage

456

457

```python

458

from social_core.backends.google import GoogleOAuth2

459

460

# Initialize backend

461

backend = GoogleOAuth2(

462

strategy=my_strategy,

463

redirect_uri='https://myapp.com/auth/complete/google/'

464

)

465

466

# Start authentication flow

467

auth_response = backend.start() # Returns redirect to Google

468

469

# In callback handler, complete authentication

470

user = backend.complete(user=current_user)

471

```

472

473

### Custom Backend Implementation

474

475

```python

476

from social_core.backends.oauth import BaseOAuth2

477

478

class CustomOAuth2(BaseOAuth2):

479

"""Custom OAuth 2.0 provider backend."""

480

name = 'custom-provider'

481

AUTHORIZATION_URL = 'https://provider.com/oauth/authorize'

482

ACCESS_TOKEN_URL = 'https://provider.com/oauth/token'

483

ACCESS_TOKEN_METHOD = 'POST'

484

ID_KEY = 'id'

485

486

def get_user_details(self, response):

487

"""Extract user details from provider response."""

488

return {

489

'username': response.get('login'),

490

'email': response.get('email'),

491

'first_name': response.get('name', '').split(' ')[0],

492

}

493

494

def user_data(self, access_token, *args, **kwargs):

495

"""Fetch user data from provider API."""

496

return self.get_json(

497

'https://provider.com/api/user',

498

headers={'Authorization': f'Bearer {access_token}'}

499

)

500

```

501

502

### Backend Configuration

503

504

Backends are configured through settings with provider-specific keys:

505

506

```python

507

# Google OAuth 2.0 configuration

508

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'your-client-id'

509

SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'your-client-secret'

510

SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['openid', 'email', 'profile']

511

512

# GitHub OAuth 2.0 configuration

513

SOCIAL_AUTH_GITHUB_KEY = 'your-github-client-id'

514

SOCIAL_AUTH_GITHUB_SECRET = 'your-github-client-secret'

515

SOCIAL_AUTH_GITHUB_SCOPE = ['user:email']

516

517

# SAML configuration

518

SOCIAL_AUTH_SAML_SP_ENTITY_ID = 'https://myapp.com'

519

SOCIAL_AUTH_SAML_SP_PUBLIC_CERT = '/path/to/cert.pem'

520

SOCIAL_AUTH_SAML_SP_PRIVATE_KEY = '/path/to/key.pem'

521

```

522

523

The extensive backend collection covers major social platforms, enterprise identity providers, and specialized services, enabling integration with virtually any OAuth, OpenID Connect, or SAML-compatible authentication system.