or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdauthorization.mdcore-setup.mddatabase.mdindex.mdpassword-management.mdregistration.mdtwo-factor.mdunified-signin.mdutilities.mdwebauthn.md

index.mddocs/

0

# Flask-Security

1

2

A comprehensive security extension for Flask applications that provides authentication, authorization, registration, password recovery, email confirmation, two-factor authentication, WebAuthn support, and unified signin capabilities. Flask-Security implements OWASP security best practices with a batteries-included approach supporting multiple database backends, internationalization, various password hashing algorithms, session management, role-based access control, and extensive customization options.

3

4

## Package Information

5

6

- **Package Name**: Flask-Security

7

- **Language**: Python

8

- **Installation**: `pip install Flask-Security`

9

- **Version**: 5.6.2

10

11

## Core Imports

12

13

```python

14

from flask_security import Security

15

```

16

17

Common imports for authentication and authorization:

18

19

```python

20

from flask_security import (

21

Security,

22

UserMixin,

23

RoleMixin,

24

login_required,

25

roles_required,

26

current_user

27

)

28

```

29

30

## Basic Usage

31

32

```python

33

from flask import Flask

34

from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required

35

from flask_sqlalchemy import SQLAlchemy

36

37

app = Flask(__name__)

38

app.config['SECRET_KEY'] = 'super-secret'

39

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'

40

41

db = SQLAlchemy(app)

42

43

# Define models

44

class Role(db.Model, RoleMixin):

45

id = db.Column(db.Integer(), primary_key=True)

46

name = db.Column(db.String(80), unique=True)

47

48

class User(db.Model, UserMixin):

49

id = db.Column(db.Integer, primary_key=True)

50

email = db.Column(db.String(255), unique=True)

51

password = db.Column(db.String(255))

52

active = db.Column(db.Boolean(), default=True)

53

54

# Setup Flask-Security

55

user_datastore = SQLAlchemyUserDatastore(db, User, Role)

56

security = Security(app, user_datastore)

57

58

@app.route('/profile')

59

@login_required

60

def profile():

61

return f'Hello {current_user.email}!'

62

63

if __name__ == '__main__':

64

with app.app_context():

65

db.create_all()

66

app.run(debug=True)

67

```

68

69

## Architecture

70

71

Flask-Security uses a modular architecture with several key components:

72

73

- **Security Class**: Main extension for Flask app initialization and configuration

74

- **Datastore Layer**: Abstracts database operations across different ORMs (SQLAlchemy, MongoEngine, Peewee, Pony)

75

- **User/Role Mixins**: Provide standard methods and properties for user and role models

76

- **Authentication Layer**: Handles login, logout, token management, and session handling

77

- **Authorization Layer**: Manages role-based and permission-based access control

78

- **Form System**: Customizable forms for all security operations (login, registration, password reset, etc.)

79

- **Signal System**: Event hooks for extending functionality (user_authenticated, password_changed, etc.)

80

- **Feature Modules**: Optional components like two-factor auth, WebAuthn, unified signin

81

82

This architecture enables Flask-Security to integrate seamlessly with existing Flask applications while providing comprehensive security features through a unified, consistent API.

83

84

## Capabilities

85

86

### Core Setup & Configuration

87

88

Essential classes and functions for initializing Flask-Security in your application, including the main Security extension class and core user/role mixins.

89

90

```python { .api }

91

class Security:

92

def __init__(self, app=None, datastore=None, **kwargs): ...

93

94

class UserMixin:

95

def is_authenticated(self) -> bool: ...

96

def is_active(self) -> bool: ...

97

def is_anonymous(self) -> bool: ...

98

def get_id(self) -> str: ...

99

100

class RoleMixin:

101

def __eq__(self, other) -> bool: ...

102

def __ne__(self, other) -> bool: ...

103

104

def current_user(): ...

105

```

106

107

[Core Setup](./core-setup.md)

108

109

### User Authentication

110

111

Authentication decorators, login/logout functions, and session management for controlling access to protected resources.

112

113

```python { .api }

114

def login_required(func): ...

115

def auth_required(*auth_methods): ...

116

def login_user(user, remember=False, duration=None, force=False, fresh=True): ...

117

def logout_user(): ...

118

def verify_password(password: str, password_hash: str) -> bool: ...

119

```

120

121

[Authentication](./authentication.md)

122

123

### User Registration & Confirmation

124

125

User registration forms, email confirmation workflow, and account activation functionality.

126

127

```python { .api }

128

class RegisterForm(Form): ...

129

class ConfirmRegisterForm(Form): ...

130

def register_user(**kwargs): ...

131

def send_confirmation_instructions(user): ...

132

def confirm_user(user): ...

133

```

134

135

[Registration](./registration.md)

136

137

### Password Management

138

139

Password hashing, validation, reset workflows, and security utilities for managing user passwords.

140

141

```python { .api }

142

def hash_password(password: str) -> str: ...

143

class ChangePasswordForm(Form): ...

144

class ForgotPasswordForm(Form): ...

145

class ResetPasswordForm(Form): ...

146

def send_reset_password_instructions(user): ...

147

```

148

149

[Password Management](./password-management.md)

150

151

### Role-Based Access Control

152

153

Authorization decorators, role management, and permission-based access control for implementing fine-grained security policies.

154

155

```python { .api }

156

def roles_required(*roles): ...

157

def roles_accepted(*roles): ...

158

def permissions_required(*permissions): ...

159

def permissions_accepted(*permissions): ...

160

```

161

162

[Authorization](./authorization.md)

163

164

### Two-Factor Authentication

165

166

TOTP-based two-factor authentication, SMS support, recovery codes, and backup authentication methods.

167

168

```python { .api }

169

class TwoFactorSetupForm(Form): ...

170

class TwoFactorVerifyCodeForm(Form): ...

171

def tf_send_security_token(user, method): ...

172

class Totp:

173

def generate_password(self) -> str: ...

174

def verify(self, token: str, window: int = 0) -> bool: ...

175

```

176

177

[Two-Factor Authentication](./two-factor.md)

178

179

### WebAuthn Support

180

181

WebAuthn/FIDO2 authentication for passwordless and phishing-resistant authentication using hardware security keys and biometrics.

182

183

```python { .api }

184

class WebAuthnRegisterForm(Form): ...

185

class WebAuthnSigninForm(Form): ...

186

class WebAuthnMixin:

187

def webauthn_credentials(self): ...

188

```

189

190

[WebAuthn](./webauthn.md)

191

192

### Unified Signin

193

194

Unified signin interface supporting multiple authentication methods (password, WebAuthn, magic links) through a single form.

195

196

```python { .api }

197

class UnifiedSigninForm(Form): ...

198

class UnifiedVerifyForm(Form): ...

199

def us_send_security_token(user, method): ...

200

```

201

202

[Unified Signin](./unified-signin.md)

203

204

### Database Integration

205

206

Datastore classes and database abstraction layer supporting multiple ORMs and databases.

207

208

```python { .api }

209

class UserDatastore:

210

def get_user(self, identifier): ...

211

def create_user(self, **kwargs): ...

212

def delete_user(self, user): ...

213

214

class SQLAlchemyUserDatastore(UserDatastore): ...

215

class MongoEngineUserDatastore(UserDatastore): ...

216

class PeeweeUserDatastore(UserDatastore): ...

217

```

218

219

[Database Integration](./database.md)

220

221

### Utility Functions

222

223

Helper functions for URLs, tokens, validation, and other common security operations.

224

225

```python { .api }

226

def url_for_security(endpoint: str, **values) -> str: ...

227

def get_hmac(password: str) -> str: ...

228

def send_mail(subject: str, recipient: str, template: str, **context): ...

229

def lookup_identity(identity: str): ...

230

```

231

232

[Utilities](./utilities.md)

233

234

## Configuration

235

236

Flask-Security provides extensive configuration options through Flask's config system. Key configuration variables include:

237

238

- `SECURITY_PASSWORD_SALT`: Salt for password hashing

239

- `SECURITY_LOGIN_URL`: Login page URL endpoint

240

- `SECURITY_LOGOUT_URL`: Logout URL endpoint

241

- `SECURITY_REGISTERABLE`: Enable user registration

242

- `SECURITY_RECOVERABLE`: Enable password recovery

243

- `SECURITY_CONFIRMABLE`: Enable email confirmation

244

- `SECURITY_TWO_FACTOR`: Enable two-factor authentication

245

- `SECURITY_WEBAUTHN`: Enable WebAuthn support

246

247

## Error Handling

248

249

Flask-Security raises specific exceptions for various error conditions:

250

251

- **`BadSignature`**: Invalid or tampered tokens

252

- **`SignatureExpired`**: Expired tokens

253

- **`EmailValidateException`**: Email validation errors

254

255

## Signals

256

257

Flask-Security emits signals for key events that applications can listen to:

258

259

- **`user_authenticated`**: User successfully logged in

260

- **`user_registered`**: New user registered

261

- **`password_changed`**: User changed password

262

- **`tf_code_confirmed`**: Two-factor code verified