or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

basic-auth.mddigest-auth.mdindex.mdmulti-auth.mdroles.mdtoken-auth.md

token-auth.mddocs/

0

# Token Authentication

1

2

Token-based HTTP authentication supporting Bearer tokens, JWT tokens, API keys, and custom authentication schemes. Token auth is ideal for API authentication, single-page applications, and stateless authentication patterns.

3

4

## Capabilities

5

6

### HTTPTokenAuth Class

7

8

Creates a token-based authentication handler with configurable schemes and custom header support.

9

10

```python { .api }

11

class HTTPTokenAuth(HTTPAuth):

12

def __init__(self, scheme='Bearer', realm=None, header=None):

13

"""

14

Initialize token authentication handler.

15

16

Parameters:

17

- scheme (str): Authentication scheme, defaults to 'Bearer'

18

- realm (str, optional): Authentication realm, defaults to 'Authentication Required'

19

- header (str, optional): Custom header name, defaults to 'Authorization'

20

"""

21

```

22

23

### Token Verification

24

25

Register callback functions for token validation and user identification.

26

27

```python { .api }

28

def verify_token(self, f):

29

"""

30

Decorator to register token verification callback.

31

32

Parameters:

33

- f (function): Callback function(token) -> user_object or None

34

35

Returns:

36

The decorated function

37

38

Usage:

39

@auth.verify_token

40

def verify_token(token):

41

# Validate token and return user object if valid

42

return user if valid else None

43

"""

44

```

45

46

### Route Protection

47

48

Protect Flask routes with token authentication using the login_required decorator.

49

50

```python { .api }

51

def login_required(self, f=None, role=None, optional=None):

52

"""

53

Decorator to require token authentication for Flask routes.

54

55

Parameters:

56

- f (function, optional): Flask route function to protect

57

- role (str|list, optional): Required user role(s)

58

- optional (bool, optional): Make authentication optional

59

60

Returns:

61

Decorated function or decorator

62

63

Usage:

64

@auth.login_required

65

def protected_api():

66

return {"user": auth.current_user()}

67

68

@auth.login_required(role='admin')

69

def admin_api():

70

return {"message": "Admin access granted"}

71

"""

72

```

73

74

### User Information

75

76

Access current authenticated user information within protected routes.

77

78

```python { .api }

79

def current_user(self):

80

"""

81

Get current authenticated user object.

82

83

Returns:

84

User object returned by verify_token callback, or None if not authenticated

85

"""

86

87

def username(self):

88

"""

89

Get current authenticated username.

90

91

Returns:

92

str: Username from token verification, or empty string if not authenticated

93

"""

94

```

95

96

## Usage Examples

97

98

### Bearer Token Authentication

99

100

```python

101

from flask import Flask

102

from flask_httpauth import HTTPTokenAuth

103

104

app = Flask(__name__)

105

auth = HTTPTokenAuth('Bearer')

106

107

# Simple token storage

108

tokens = {

109

"secret-token-1": "john",

110

"secret-token-2": "susan"

111

}

112

113

@auth.verify_token

114

def verify_token(token):

115

if token in tokens:

116

return tokens[token]

117

118

@app.route('/api/data')

119

@auth.login_required

120

def get_data():

121

return {"user": auth.current_user(), "data": "sensitive information"}

122

123

# Usage: curl -H "Authorization: Bearer secret-token-1" http://localhost:5000/api/data

124

```

125

126

### JWT Token Authentication

127

128

```python

129

from flask import Flask

130

from flask_httpauth import HTTPTokenAuth

131

import jwt

132

from datetime import datetime, timedelta

133

134

app = Flask(__name__)

135

app.config['SECRET_KEY'] = 'jwt-secret-key'

136

auth = HTTPTokenAuth('Bearer')

137

138

@auth.verify_token

139

def verify_token(token):

140

try:

141

# Decode and verify JWT token

142

data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])

143

144

# Check expiration

145

if data['exp'] < datetime.utcnow().timestamp():

146

return None

147

148

return data['username']

149

except jwt.InvalidTokenError:

150

return None

151

152

@app.route('/api/protected')

153

@auth.login_required

154

def protected():

155

return {"message": f"Hello {auth.current_user()}"}

156

157

# Generate token example

158

def generate_token(username):

159

payload = {

160

'username': username,

161

'exp': datetime.utcnow() + timedelta(hours=1)

162

}

163

return jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')

164

```

165

166

### API Key Authentication

167

168

```python

169

from flask import Flask

170

from flask_httpauth import HTTPTokenAuth

171

172

app = Flask(__name__)

173

auth = HTTPTokenAuth('ApiKey')

174

175

# API key database

176

api_keys = {

177

"key-12345": {"user": "john", "permissions": ["read", "write"]},

178

"key-67890": {"user": "susan", "permissions": ["read"]}

179

}

180

181

@auth.verify_token

182

def verify_api_key(api_key):

183

if api_key in api_keys:

184

return api_keys[api_key]

185

186

@app.route('/api/read')

187

@auth.login_required

188

def read_data():

189

user_data = auth.current_user()

190

if "read" in user_data["permissions"]:

191

return {"data": "readable content"}

192

return {"error": "Insufficient permissions"}, 403

193

194

# Usage: curl -H "Authorization: ApiKey key-12345" http://localhost:5000/api/read

195

```

196

197

### Custom Header Authentication

198

199

```python

200

from flask import Flask

201

from flask_httpauth import HTTPTokenAuth

202

203

app = Flask(__name__)

204

# Use custom header instead of Authorization

205

auth = HTTPTokenAuth(scheme='Token', header='X-API-Key')

206

207

tokens = {

208

"custom-token-123": "john",

209

"custom-token-456": "susan"

210

}

211

212

@auth.verify_token

213

def verify_token(token):

214

return tokens.get(token)

215

216

@app.route('/api/data')

217

@auth.login_required

218

def get_data():

219

return {"user": auth.current_user()}

220

221

# Usage: curl -H "X-API-Key: custom-token-123" http://localhost:5000/api/data

222

```

223

224

### Database Token Verification

225

226

```python

227

from flask import Flask

228

from flask_httpauth import HTTPTokenAuth

229

import hashlib

230

import secrets

231

232

app = Flask(__name__)

233

auth = HTTPTokenAuth('Bearer')

234

235

class TokenManager:

236

def __init__(self):

237

# In real apps, use database

238

self.tokens = {}

239

240

def create_token(self, username):

241

token = secrets.token_urlsafe(32)

242

token_hash = hashlib.sha256(token.encode()).hexdigest()

243

self.tokens[token_hash] = {

244

'username': username,

245

'created': datetime.utcnow()

246

}

247

return token

248

249

def verify_token(self, token):

250

token_hash = hashlib.sha256(token.encode()).hexdigest()

251

token_data = self.tokens.get(token_hash)

252

253

if token_data:

254

# Check if token is still valid (24 hours)

255

if datetime.utcnow() - token_data['created'] < timedelta(hours=24):

256

return token_data['username']

257

else:

258

# Remove expired token

259

del self.tokens[token_hash]

260

261

return None

262

263

token_manager = TokenManager()

264

265

@auth.verify_token

266

def verify_token(token):

267

return token_manager.verify_token(token)

268

269

@app.route('/login', methods=['POST'])

270

def login():

271

# Simplified login - in real apps, verify username/password

272

username = request.json.get('username')

273

token = token_manager.create_token(username)

274

return {"token": token}

275

276

@app.route('/api/protected')

277

@auth.login_required

278

def protected():

279

return {"user": auth.current_user()}

280

```

281

282

## Token Schemes

283

284

Flask-HTTPAuth supports various token authentication schemes:

285

286

- **Bearer**: Standard OAuth 2.0 bearer tokens (`Authorization: Bearer <token>`)

287

- **Token**: Simple token scheme (`Authorization: Token <token>`)

288

- **ApiKey**: API key scheme (`Authorization: ApiKey <key>`)

289

- **Custom**: Any custom scheme name (`Authorization: CustomScheme <token>`)

290

291

## Error Handling

292

293

Token authentication handles authentication errors automatically:

294

295

- **401 Unauthorized**: Invalid token, expired token, or missing authentication

296

- **403 Forbidden**: Valid token but insufficient role permissions

297

- **WWW-Authenticate header**: Automatically added with scheme information

298

- **Token Validation**: Automatic token extraction and verification

299

300

Custom error responses can be implemented using the `error_handler` decorator inherited from the base HTTPAuth class.