Authentication
The Blocklet SDK provides robust middleware for handling user authentication and authorization within your Blocklet applications. This section details the session
middleware, which is crucial for identifying users, and the auth
middleware, for enforcing access control based on roles, permissions, and KYC status.
For an overview of all available Express.js middleware, refer to the Middleware Reference.
Session Middleware#
The session
middleware is designed to authenticate incoming requests by verifying various tokens and populating the req.user
object with SessionUser
information. It supports authentication via login tokens, access keys, component calls, and signed temporary tokens.
Authentication Flow#
Here's a high-level overview of how the session
middleware processes authentication:
Usage#
To use the session
middleware, you can import it from @blocklet/sdk/middlewares
and configure it with various options to enable or disable specific authentication methods.
import express from 'express';
import { session } from '@blocklet/sdk/middlewares';
const app = express();
// Basic usage: enables login token and access key authentication by default
app.use(session());
// Advanced usage: enable specific authentication methods
app.use(session({
loginToken: true, // Enable authentication by login_token cookie
componentCall: false, // Disable authentication by component call headers
signedToken: true, // Enable authentication by signed token
accessKey: true, // Enable authentication by access key
strictMode: false // Do not throw an error if token verification fails, just set req.user to null
}));
app.get('/api/user', (req, res) => {
if (req.user) {
res.json({ user: req.user });
} else {
res.status(401).json({ error: 'Not authenticated' });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
SessionOptions
Parameters#
Name | Type | Description | Default |
---|---|---|---|
|
| If |
|
|
| If |
|
|
| If |
|
|
| If |
|
|
| If |
|
|
| The name of the query parameter that carries the signed token when |
|
SessionUser
Return Value#
When authentication is successful, the req.user
object will be populated with the following SessionUser
properties:
Name | Type | Description |
---|---|---|
|
| The DID of the authenticated user. |
|
| The role assigned to the user (e.g., |
|
| The authentication provider (e.g., |
|
| The full name of the user. |
|
| The operating system of the user's DID Wallet (e.g., |
|
| Indicates if the user's email is verified. |
|
| Indicates if the user's phone is verified. |
|
| The authentication method used for the current session ( |
|
| A bitmask representing KYC status. This is decoded into |
Example req.user
Object:
{
"did": "did:abt:zxxxxx",
"role": "user",
"provider": "wallet",
"fullName": "John Doe",
"walletOS": "ios",
"emailVerified": true,
"phoneVerified": false,
"method": "loginToken"
}
Authorization Middleware#
The auth
middleware provides fine-grained access control based on user roles, permissions, KYC status, and the authentication method used. It works in conjunction with the session
middleware, expecting req.user
to be populated.
Usage#
import express from 'express';
import { session, auth } from '@blocklet/sdk/middlewares';
const app = express();
// First, ensure the session middleware runs to populate req.user
app.use(session());
// Protect an admin-only route
app.get('/api/admin-data', auth({ roles: ['admin'] }), (req, res) => {
res.json({ message: 'Welcome, admin!', user: req.user });
});
// Protect a route requiring specific permissions
app.get('/api/edit-content', auth({ permissions: ['content:write', 'content:edit'] }), (req, res) => {
res.json({ message: 'You can edit content.', user: req.user });
});
// Protect a route requiring email KYC verification
app.get('/api/verified-feature', auth({ kyc: ['email'] }), (req, res) => {
res.json({ message: 'Your email is verified!', user: req.user });
});
// Protect a route accessible only via login token authentication
app.get('/api/secure-endpoint', auth({ methods: ['loginToken'] }), (req, res) => {
res.json({ message: 'Accessed via login token.', user: req.user });
});
app.listen(3000, () => console.log('Server running on port 3000'));
AuthOptions
Parameters#
Name | Type | Description |
---|---|---|
|
| An array of roles. The user must have at least one of the specified roles to access the resource. If the user's role is not in this array, a |
|
| An array of permission names. The user must possess at least one of these permissions to access the resource. Permissions are typically fetched from Blocklet Server based on the user's role. If no matching permission is found, a |
|
| An array of KYC methods ( |
|
| An array of allowed authentication methods ( |
|
| An optional function that returns an |
Authorization Checks#
The auth
middleware performs checks in the following order, returning 403 Forbidden
if any check fails:
- User DID: Verifies
req.user.did
orx-user-did
header exists. If not,401 Unauthorized
is returned. - Roles: If
roles
option is provided, checks ifreq.user.role
is included in the specified roles. - Permissions: If
permissions
option is provided, fetches permissions associated withreq.user.role
from Blocklet Server and checks if any required permission is present. - KYC Status: If
kyc
option is provided, decodesreq.user.kyc
(a bitmask) and verifies if the required KYC methods (e.g., email, phone) are verified. - Auth Method: If
methods
option is provided, checks ifreq.user.method
is one of the allowed authentication methods.
Conclusion#
The session
and auth
middlewares are essential components for securing your Blocklet applications by handling user authentication and enforcing authorization rules. Properly configuring these middlewares ensures that only authenticated and authorized users can access sensitive resources. To learn about protecting your application against common web vulnerabilities, proceed to the CSRF Protection section.