0
# Authentication & Authorization
1
2
LoopBack's comprehensive authentication and authorization system provides user management, access tokens, role-based access control, and fine-grained ACL permissions through built-in models and middleware.
3
4
## Capabilities
5
6
### User Management
7
8
Built-in User model with authentication, email verification, and password management.
9
10
```javascript { .api }
11
/**
12
* User model for authentication and user management
13
*/
14
const User = loopback.User;
15
16
// Static authentication methods
17
/**
18
* Authenticate user with credentials
19
* @param {Object} credentials - Login credentials
20
* @param {string} credentials.email - User email
21
* @param {string} credentials.password - User password
22
* @param {string|Object} include - Relations to include in response
23
* @param {Function} callback - Callback function
24
*/
25
User.login(credentials, include, callback);
26
27
/**
28
* Logout user by token ID
29
* @param {string} tokenId - Access token ID
30
* @param {Function} callback - Callback function
31
*/
32
User.logout(tokenId, callback);
33
34
// Instance authentication methods
35
/**
36
* Login this user instance
37
* @param {Object} credentials - Login credentials
38
* @param {string|Object} include - Relations to include
39
* @param {Function} callback - Callback function
40
*/
41
user.login(credentials, include, callback);
42
43
/**
44
* Logout this user instance
45
* @param {string} tokenId - Access token ID
46
* @param {Function} callback - Callback function
47
*/
48
user.logout(tokenId, callback);
49
50
/**
51
* Send email verification
52
* @param {Object} options - Verification options
53
* @param {string} options.type - Verification type ('email')
54
* @param {string} options.to - Email address to send to
55
* @param {string} options.from - From email address
56
* @param {string} options.subject - Email subject
57
* @param {string} options.redirect - Redirect URL after verification
58
* @param {Function} callback - Callback function
59
*/
60
user.verify(options, callback);
61
62
/**
63
* Confirm email verification
64
* @param {string} uid - User ID
65
* @param {string} token - Verification token
66
* @param {string} redirect - Redirect URL
67
* @param {Function} callback - Callback function
68
*/
69
user.confirm(uid, token, redirect, callback);
70
71
/**
72
* Reset password via email
73
* @param {Object} options - Reset options
74
* @param {string} options.email - User email address
75
* @param {Function} callback - Callback function
76
*/
77
user.resetPassword(options, callback);
78
79
/**
80
* Change user password
81
* @param {string} oldPassword - Current password
82
* @param {string} newPassword - New password
83
* @param {Function} callback - Callback function
84
*/
85
user.changePassword(oldPassword, newPassword, callback);
86
87
/**
88
* Set user password
89
* @param {string} newPassword - New password
90
* @param {Function} callback - Callback function
91
*/
92
user.setPassword(newPassword, callback);
93
94
/**
95
* Create access token for this user
96
* @param {Object} data - Token data
97
* @param {Object} options - Creation options
98
* @param {Function} callback - Callback function
99
*/
100
user.createAccessToken(data, options, callback);
101
102
/**
103
* Verify if plain text password matches user's password
104
* @param {string} plain - Plain text password
105
* @param {Function} callback - Callback function
106
*/
107
user.hasPassword(plain, callback);
108
```
109
110
**User Model Properties:**
111
112
```javascript { .api }
113
interface UserProperties {
114
id: any; // User ID
115
username: string; // Username (optional)
116
password: string; // Hashed password
117
email: string; // Email address (required)
118
emailVerified: boolean; // Email verification status
119
verificationToken: string; // Email verification token
120
realm: string; // User realm (optional)
121
created: Date; // Creation timestamp
122
lastUpdated: Date; // Last update timestamp
123
}
124
```
125
126
**Usage Example:**
127
128
```javascript
129
const User = app.models.User;
130
131
// Register new user
132
User.create({
133
email: 'user@example.com',
134
password: 'secret123'
135
}, (err, user) => {
136
if (err) return console.error(err);
137
138
// Send verification email
139
user.verify({
140
type: 'email',
141
to: user.email,
142
from: 'noreply@myapp.com',
143
subject: 'Verify your email',
144
redirect: '/verified'
145
}, (err, result) => {
146
console.log('Verification email sent');
147
});
148
});
149
150
// Login user
151
User.login({
152
email: 'user@example.com',
153
password: 'secret123'
154
}, 'user', (err, token) => {
155
if (err) return console.error(err);
156
console.log('Access token:', token.id);
157
console.log('User:', token.user);
158
});
159
```
160
161
### Access Token Management
162
163
Built-in AccessToken model for managing authentication tokens.
164
165
```javascript { .api }
166
/**
167
* AccessToken model for authentication tokens
168
*/
169
const AccessToken = loopback.AccessToken;
170
171
/**
172
* AccessToken properties
173
*/
174
interface AccessTokenProperties {
175
id: string; // Token ID (the actual token)
176
ttl: number; // Time to live in seconds
177
scopes: string[]; // Allowed scopes
178
created: Date; // Creation timestamp
179
userId: any; // Associated user ID
180
}
181
182
/**
183
* AccessToken relationships
184
*/
185
interface AccessTokenRelations {
186
user: User; // belongsTo User
187
}
188
```
189
190
### Application Management
191
192
Built-in Application model for registering client applications.
193
194
```javascript { .api }
195
/**
196
* Application model for client application registration
197
*/
198
const Application = loopback.Application;
199
200
/**
201
* Application properties
202
*/
203
interface ApplicationProperties {
204
id: string; // Application ID
205
name: string; // Application name
206
description: string; // Application description
207
icon: string; // Application icon URL
208
owner: string; // Owner user ID
209
collaborators: string[]; // Collaborator user IDs
210
email: string; // Contact email
211
url: string; // Application URL
212
callbackUrls: string[]; // OAuth callback URLs
213
permissions: string[]; // Granted permissions
214
}
215
```
216
217
### Role-Based Access Control
218
219
Built-in Role and RoleMapping models for role-based permissions.
220
221
```javascript { .api }
222
/**
223
* Role model for defining user roles
224
*/
225
const Role = loopback.Role;
226
227
/**
228
* Check if principal is in role
229
* @param {string} role - Role name or ID
230
* @param {Object} context - Access context
231
* @param {Function} callback - Callback function
232
*/
233
Role.isInRole(role, context, callback);
234
235
/**
236
* Get roles for context
237
* @param {Object} context - Access context
238
* @param {Function} callback - Callback function
239
*/
240
Role.getRoles(context, callback);
241
242
/**
243
* Role properties
244
*/
245
interface RoleProperties {
246
id: any; // Role ID
247
name: string; // Role name (unique)
248
description: string; // Role description
249
created: Date; // Creation timestamp
250
modified: Date; // Last modification timestamp
251
}
252
253
/**
254
* RoleMapping model for assigning roles to principals
255
*/
256
const RoleMapping = loopback.RoleMapping;
257
258
/**
259
* RoleMapping properties
260
*/
261
interface RoleMappingProperties {
262
id: any; // Mapping ID
263
principalType: string; // Principal type (USER, APP, ROLE)
264
principalId: string; // Principal ID
265
roleId: any; // Role ID
266
}
267
268
/**
269
* Principal types
270
*/
271
const Principal = {
272
USER: 'USER',
273
APP: 'APP',
274
ROLE: 'ROLE'
275
};
276
```
277
278
**Usage Example:**
279
280
```javascript
281
const Role = app.models.Role;
282
const RoleMapping = app.models.RoleMapping;
283
284
// Create admin role
285
Role.create({
286
name: 'admin',
287
description: 'Administrator role'
288
}, (err, role) => {
289
if (err) return console.error(err);
290
291
// Assign role to user
292
RoleMapping.create({
293
principalType: 'USER',
294
principalId: userId,
295
roleId: role.id
296
}, (err, mapping) => {
297
console.log('User assigned to admin role');
298
});
299
});
300
```
301
302
### Access Control Lists (ACL)
303
304
Built-in ACL model for fine-grained permission control.
305
306
```javascript { .api }
307
/**
308
* ACL model for access control rules
309
*/
310
const ACL = loopback.ACL;
311
312
/**
313
* Check permission for context
314
* @param {Object} context - Access context
315
* @param {Function} callback - Callback function
316
*/
317
ACL.checkPermission(context, callback);
318
319
/**
320
* Check access for context
321
* @param {Object} context - Access context
322
* @param {Function} callback - Callback function
323
*/
324
ACL.checkAccessForContext(context, callback);
325
326
/**
327
* ACL properties
328
*/
329
interface ACLProperties {
330
id: any; // ACL ID
331
model: string; // Model name (* for all)
332
property: string; // Property name (* for all)
333
accessType: string; // Access type (READ, WRITE, EXECUTE, *)
334
permission: string; // Permission (ALLOW, DENY)
335
principalType: string; // Principal type (USER, APP, ROLE)
336
principalId: string; // Principal ID
337
}
338
339
/**
340
* Access types
341
*/
342
const AccessType = {
343
READ: 'READ',
344
WRITE: 'WRITE',
345
EXECUTE: 'EXECUTE',
346
ALL: '*'
347
};
348
349
/**
350
* Permission types
351
*/
352
const Permission = {
353
ALLOW: 'ALLOW',
354
DENY: 'DENY'
355
};
356
```
357
358
### Access Context System
359
360
Access context objects for permission checking.
361
362
```javascript { .api }
363
/**
364
* Access context for permission evaluation
365
*/
366
class AccessContext {
367
/**
368
* Create access context
369
* @param {Object} context - Context properties
370
*/
371
constructor(context);
372
373
/**
374
* Add principal to context
375
* @param {string} type - Principal type (USER, APP, ROLE)
376
* @param {*} id - Principal ID
377
* @param {string} name - Principal name
378
*/
379
addPrincipal(type, id, name);
380
381
/**
382
* Get user ID from context
383
* @returns {*} User ID
384
*/
385
getUserId();
386
387
/**
388
* Get user object from context
389
* @returns {User} User instance
390
*/
391
getUser();
392
393
/**
394
* Get application ID from context
395
* @returns {*} Application ID
396
*/
397
getAppId();
398
399
/**
400
* Check if context is authenticated
401
* @returns {boolean} True if authenticated
402
*/
403
isAuthenticated();
404
405
/**
406
* Get allowed scopes
407
* @returns {string[]} Array of scope names
408
*/
409
getScopes();
410
411
/**
412
* Check if scope is allowed
413
* @param {string} scope - Scope name
414
* @returns {boolean} True if scope is allowed
415
*/
416
isScopeAllowed(scope);
417
}
418
419
/**
420
* Principal representation in access context
421
*/
422
class Principal {
423
/**
424
* Create principal
425
* @param {string} type - Principal type
426
* @param {*} id - Principal ID
427
* @param {string} name - Principal name
428
*/
429
constructor(type, id, name);
430
431
/**
432
* Compare with another principal
433
* @param {Principal} otherPrincipal - Principal to compare
434
* @returns {boolean} True if principals are equal
435
*/
436
equals(otherPrincipal);
437
}
438
439
/**
440
* Access request for permission checking
441
*/
442
class AccessRequest {
443
/**
444
* Create access request
445
* @param {string} model - Model name
446
* @param {string} property - Property name
447
* @param {string} accessType - Access type
448
* @param {string} permission - Permission
449
* @param {string[]} methodNames - Method names
450
* @param {Registry} registry - Model registry
451
*/
452
constructor(model, property, accessType, permission, methodNames, registry);
453
454
/**
455
* Check if request uses wildcard
456
* @returns {boolean} True if wildcard access
457
*/
458
isWildcard();
459
460
/**
461
* Check if request exactly matches ACL
462
* @param {Object} acl - ACL object
463
* @returns {boolean} True if exact match
464
*/
465
exactlyMatches(acl);
466
467
/**
468
* Check if request is allowed
469
* @returns {boolean} True if allowed
470
*/
471
isAllowed();
472
}
473
```
474
475
### Scope Management
476
477
Built-in Scope model for managing permission scopes.
478
479
```javascript { .api }
480
/**
481
* Scope model for permission scopes
482
*/
483
const Scope = loopback.Scope;
484
485
/**
486
* Scope properties
487
*/
488
interface ScopeProperties {
489
id: any; // Scope ID
490
name: string; // Scope name
491
description: string; // Scope description
492
}
493
```
494
495
**Usage Example:**
496
497
```javascript
498
// Define ACL rules in model definition
499
const Product = loopback.createModel('Product', {
500
name: String,
501
price: Number
502
}, {
503
acls: [
504
// Deny all access by default
505
{
506
accessType: '*',
507
principalType: 'ROLE',
508
principalId: '$everyone',
509
permission: 'DENY'
510
},
511
// Allow authenticated users to read
512
{
513
accessType: 'READ',
514
principalType: 'ROLE',
515
principalId: '$authenticated',
516
permission: 'ALLOW'
517
},
518
// Allow admin role full access
519
{
520
accessType: '*',
521
principalType: 'ROLE',
522
principalId: 'admin',
523
permission: 'ALLOW'
524
}
525
]
526
});
527
```
528
529
## Email Verification and Password Reset
530
531
```javascript { .api }
532
/**
533
* Email model for sending emails
534
*/
535
const Email = loopback.Email;
536
537
/**
538
* Send email
539
* @param {Object} options - Email options
540
* @param {string} options.to - Recipient email
541
* @param {string} options.from - Sender email
542
* @param {string} options.subject - Email subject
543
* @param {string} options.text - Plain text content
544
* @param {string} options.html - HTML content
545
* @param {Function} callback - Callback function
546
*/
547
Email.send(options, callback);
548
```
549
550
### Additional Built-in Models
551
552
```javascript { .api }
553
/**
554
* Change model for tracking data changes
555
*/
556
const Change = loopback.Change;
557
558
/**
559
* Checkpoint model for replication synchronization
560
*/
561
const Checkpoint = loopback.Checkpoint;
562
563
/**
564
* Key-value model for simple key-value storage
565
*/
566
const KeyValueModel = loopback.KeyValueModel;
567
```
568
569
**Usage Example:**
570
571
```javascript
572
const Email = app.models.Email;
573
574
Email.send({
575
to: 'user@example.com',
576
from: 'noreply@myapp.com',
577
subject: 'Welcome!',
578
html: '<h1>Welcome to our app!</h1>'
579
}, (err, result) => {
580
if (err) return console.error(err);
581
console.log('Email sent successfully');
582
});
583
```