Session Middleware
The session middleware is a core component of the Blocklet SDK's authentication system. It acts as a gatekeeper for your Express.js routes, verifying the identity of the requester and, upon successful authentication, attaching a SessionUser object to the req.user property. This allows subsequent middleware and route handlers to access authenticated user information easily.
The middleware is highly flexible, supporting several authentication strategies out of the box, including login tokens from DID Connect, programmatic access keys, and secure inter-component calls.
How It Works#
The session middleware inspects incoming requests for credentials in a specific order of priority. If a valid credential is found, it populates req.user and passes control to the next handler. If no valid credential is found, its behavior depends on whether strictMode is enabled.
An additional security check is performed if the enableBlacklist feature is turned on in your blocklet's settings. Before validating a login token, the middleware will call a service API to ensure the token has not been revoked or blocked.
Basic Usage#
You can apply the session middleware to your entire application or to specific routes that require authentication.
Applying Session Middleware
import express from 'express';
import session from '@blocklet/sdk/middlewares/session';
const app = express();
// Apply to all routes
app.use(session());
// Or apply to a specific route that must be protected
app.get('/api/profile', session({ strictMode: true }), (req, res) => {
// In strict mode, if req.user is not present, the middleware would have already sent a 401 response.
if (req.user) {
res.json(req.user);
}
});
// A public route that behaves differently for logged-in users
app.get('/api/info', session(), (req, res) => {
if (req.user) {
res.json({ message: `Hello, ${req.user.fullName}`});
} else {
// In non-strict mode, req.user is undefined for unauthenticated users
res.json({ message: 'Hello, guest.' });
}
});See all 4 lines
Configuration Options#
The sessionMiddleware function accepts an optional configuration object to tailor its behavior.
Example Configurations#
Strict API Endpoint
For endpoints that must be protected, `strictMode` ensures unauthenticated requests are rejected immediately.
```javascript
app.use('/api/admin', session({ strictMode: true }));
```Enable Access Keys
The SessionUser Object#
When authentication is successful, the req.user object is populated with the following structure. This object provides essential information about the authenticated user or component.
Here is an example of what the req.user object might look like after a successful login:
Example req.user Object
{
"did": "z8iZgeJjzB6Q1bK2rR1BfA2J8cNEJ8cNEJ8c",
"role": "owner",
"fullName": "Alice",
"provider": "wallet",
"walletOS": "ios",
"emailVerified": true,
"phoneVerified": false,
"method": "loginToken"
}Next Steps#
Once a user is authenticated with the session middleware, you can perform more granular access control based on their role and permissions. Proceed to the next section to learn how to use the Authorization Middleware to protect routes based on user roles.