or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdcaching-performance.mdcomponents-config.mddisplay-elements.mdindex.mdinput-widgets.mdlayout-containers.mdnavigation-pages.mdstate-management.mduser-auth.md

user-auth.mddocs/

0

# User and Authentication

1

2

User authentication, login/logout functionality, and user information access. Streamlit provides built-in authentication capabilities for securing applications and managing user sessions.

3

4

## Capabilities

5

6

### User Information

7

8

Access current user information and profile data.

9

10

```python { .api }

11

user: UserInfoProxy

12

```

13

14

The user object provides access to authenticated user information including profile data, authentication status, and user attributes.

15

16

Example usage:

17

```python

18

# Check if user is authenticated

19

if st.user.is_authenticated:

20

st.write(f"Welcome, {st.user.email}!")

21

st.write(f"User ID: {st.user.id}")

22

23

# Access user profile

24

if hasattr(st.user, 'name'):

25

st.write(f"Name: {st.user.name}")

26

27

# Check user permissions

28

if st.user.has_permission('admin'):

29

st.write("Admin access granted")

30

else:

31

st.write("Please log in to continue")

32

```

33

34

### Authentication Functions

35

36

Functions for managing user authentication flow.

37

38

```python { .api }

39

def login(provider, *, oauth2=None):

40

"""

41

Initiate user login process with specified authentication provider.

42

43

Args:

44

provider (str): Authentication provider name

45

oauth2 (dict, optional): OAuth2 configuration parameters

46

47

Returns:

48

bool: True if login was successful

49

"""

50

51

def logout():

52

"""

53

Log out the current user and clear authentication state.

54

55

Returns:

56

bool: True if logout was successful

57

"""

58

```

59

60

Example usage:

61

```python

62

# Login with different providers

63

if not st.user.is_authenticated:

64

col1, col2, col3 = st.columns(3)

65

66

with col1:

67

if st.button("Login with Google"):

68

st.login("google")

69

70

with col2:

71

if st.button("Login with GitHub"):

72

st.login("github")

73

74

with col3:

75

if st.button("Login with Microsoft"):

76

st.login("microsoft")

77

else:

78

# User is authenticated

79

st.success(f"Logged in as {st.user.email}")

80

81

if st.button("Logout"):

82

st.logout()

83

st.rerun()

84

85

# Custom OAuth2 configuration

86

if st.button("Login with Custom Provider"):

87

oauth_config = {

88

"client_id": st.secrets["oauth_client_id"],

89

"client_secret": st.secrets["oauth_client_secret"],

90

"redirect_uri": "https://myapp.streamlit.app/auth/callback"

91

}

92

st.login("custom", oauth2=oauth_config)

93

```

94

95

### Legacy User Information (Deprecated)

96

97

Deprecated user information interface maintained for backward compatibility.

98

99

```python { .api }

100

experimental_user: DeprecatedUserInfoProxy

101

```

102

103

Example usage:

104

```python

105

# Deprecated - use st.user instead

106

if st.experimental_user.email:

107

st.write(f"User: {st.experimental_user.email}")

108

```

109

110

### Authentication Patterns

111

112

#### Basic Authentication Flow

113

114

```python

115

def show_login_page():

116

"""Display login page with provider options."""

117

st.title("Welcome")

118

st.write("Please log in to access the application")

119

120

# Provider selection

121

provider = st.selectbox(

122

"Choose login method:",

123

["google", "github", "microsoft", "azure"]

124

)

125

126

if st.button(f"Login with {provider.title()}"):

127

success = st.login(provider)

128

if success:

129

st.success("Login successful!")

130

st.rerun()

131

else:

132

st.error("Login failed. Please try again.")

133

134

def show_authenticated_app():

135

"""Display main application for authenticated users."""

136

# Header with user info and logout

137

col1, col2 = st.columns([3, 1])

138

with col1:

139

st.title("My Dashboard")

140

with col2:

141

st.write(f"👤 {st.user.email}")

142

if st.button("Logout"):

143

st.logout()

144

st.rerun()

145

146

# Main application content

147

st.write("Welcome to your dashboard!")

148

# ... rest of app

149

150

# Main app logic

151

if st.user.is_authenticated:

152

show_authenticated_app()

153

else:

154

show_login_page()

155

```

156

157

#### Role-Based Access Control

158

159

```python

160

def check_user_role():

161

"""Check user role and permissions."""

162

if not st.user.is_authenticated:

163

return None

164

165

# Get user role from profile or database

166

user_role = getattr(st.user, 'role', 'user')

167

return user_role

168

169

def require_role(required_role):

170

"""Decorator to require specific user role."""

171

def decorator(func):

172

def wrapper(*args, **kwargs):

173

current_role = check_user_role()

174

if current_role != required_role:

175

st.error(f"Access denied. {required_role.title()} role required.")

176

st.stop()

177

return func(*args, **kwargs)

178

return wrapper

179

return decorator

180

181

@require_role('admin')

182

def show_admin_panel():

183

"""Admin-only functionality."""

184

st.title("Admin Panel")

185

st.write("Admin controls here")

186

187

# Usage

188

user_role = check_user_role()

189

190

if user_role == 'admin':

191

show_admin_panel()

192

elif user_role == 'user':

193

st.title("User Dashboard")

194

st.write("User content here")

195

else:

196

st.error("Please log in to continue")

197

st.stop()

198

```

199

200

#### Session-Based User Management

201

202

```python

203

def initialize_user_session():

204

"""Initialize user session state."""

205

if "user_initialized" not in st.session_state:

206

st.session_state.user_initialized = True

207

208

if st.user.is_authenticated:

209

# Load user preferences

210

st.session_state.user_preferences = load_user_preferences(st.user.id)

211

st.session_state.user_data = load_user_data(st.user.id)

212

213

def save_user_preferences():

214

"""Save current user preferences."""

215

if st.user.is_authenticated:

216

save_preferences_to_db(st.user.id, st.session_state.user_preferences)

217

218

# Initialize on app start

219

initialize_user_session()

220

221

# User-specific functionality

222

if st.user.is_authenticated:

223

# Display personalized content

224

st.title(f"Welcome back, {getattr(st.user, 'name', st.user.email)}!")

225

226

# User preferences

227

with st.expander("Preferences"):

228

theme = st.selectbox("Theme", ["light", "dark"],

229

index=["light", "dark"].index(

230

st.session_state.get("user_preferences", {}).get("theme", "light")

231

))

232

233

if st.button("Save Preferences"):

234

st.session_state.user_preferences["theme"] = theme

235

save_user_preferences()

236

st.success("Preferences saved!")

237

```

238

239

#### Multi-Tenant Applications

240

241

```python

242

def get_user_tenant():

243

"""Get tenant information for current user."""

244

if not st.user.is_authenticated:

245

return None

246

247

# Extract tenant from user email domain or profile

248

email_domain = st.user.email.split('@')[1]

249

tenant = get_tenant_by_domain(email_domain)

250

return tenant

251

252

def load_tenant_data(tenant_id):

253

"""Load tenant-specific data and configuration."""

254

return {

255

"name": get_tenant_name(tenant_id),

256

"settings": get_tenant_settings(tenant_id),

257

"data": get_tenant_data(tenant_id)

258

}

259

260

# Multi-tenant app logic

261

if st.user.is_authenticated:

262

tenant = get_user_tenant()

263

264

if tenant:

265

# Load tenant-specific configuration

266

tenant_data = load_tenant_data(tenant.id)

267

268

# Configure app for tenant

269

st.set_page_config(

270

page_title=f"{tenant_data['name']} Dashboard",

271

page_icon=tenant.icon

272

)

273

274

st.title(f"{tenant_data['name']} Dashboard")

275

st.write(f"Welcome, {st.user.email}")

276

277

# Tenant-specific functionality

278

display_tenant_data(tenant_data['data'])

279

else:

280

st.error("No tenant found for your account")

281

else:

282

st.error("Please log in to continue")

283

```

284

285

#### Authentication Callbacks

286

287

```python

288

def on_login_success():

289

"""Handle successful login."""

290

st.session_state.login_timestamp = time.time()

291

st.session_state.user_preferences = load_user_preferences(st.user.id)

292

293

# Log login event

294

log_user_event(st.user.id, "login", {

295

"timestamp": st.session_state.login_timestamp,

296

"ip_address": st.context.headers.get("X-Forwarded-For", "unknown")

297

})

298

299

def on_logout():

300

"""Handle user logout."""

301

# Save any pending changes

302

if "user_data" in st.session_state:

303

save_user_data(st.user.id, st.session_state.user_data)

304

305

# Clear session state

306

for key in list(st.session_state.keys()):

307

if key.startswith("user_"):

308

del st.session_state[key]

309

310

# Log logout event

311

log_user_event(st.user.id, "logout", {

312

"timestamp": time.time()

313

})

314

315

# Authentication state management

316

if "auth_checked" not in st.session_state:

317

st.session_state.auth_checked = True

318

319

if st.user.is_authenticated:

320

on_login_success()

321

322

# Check for logout action

323

if st.session_state.get("logging_out", False):

324

on_logout()

325

st.logout()

326

del st.session_state.logging_out

327

st.rerun()

328

```