Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する
Middleware Reference

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:

"Blocklet Server""Blocklet Application"Client"Blocklet Server""Blocklet Application"Clientalt[Login Token][Access Key][Component Call][Signed Token]alt[Authentication Successful][Authentication Failed]Request (with login_token, access key, or other credentials)"sessionMiddleware" initiates authenticationExtract "login_token" from cookie"verifyLoginToken" (JWT verification)Verification Result (SessionUser or null/error)Extract access key"verifyAccessKey" (AuthService call)Verification Result (SessionUser or null/error)Extract signature and data from "x-component-" headers"verifyComponentCall" (Signature verification)Verification Result (SessionUser or null/error)Extract token from query param (default "__jwt")"verifySignedToken" (JWT verification with Blocklet's public key)Verification Result (SessionUser or null/error)Populate "req.user" with SessionUser dataCall "next()"Processed RequestRespond with 401 Unauthorized or 400 Bad Request

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

loginToken

boolean

If true, enables authentication via login_token found in cookies. This token is typically issued after a successful DID Connect login.

true

componentCall

boolean

If true, enables authentication for inter-component calls by verifying x-component-sig and x-component-data headers.

false

signedToken

boolean

If true, enables authentication via a temporary signed token. This token is usually passed as a query parameter.

false

strictMode

boolean

If true, token verification failures will result in a 401 Unauthorized response. If false, req.user will simply be null on failure.

false

accessKey

boolean

If true, enables authentication via an access key (e.g., blocklet-xxxxxx) passed as a bearer token or login_token cookie.

false

signedTokenKey

string

The name of the query parameter that carries the signed token when signedToken is enabled.

'__jwt'

SessionUser Return Value#

When authentication is successful, the req.user object will be populated with the following SessionUser properties:

Name

Type

Description

did

string

The DID of the authenticated user.

role

string

The role assigned to the user (e.g., 'user', 'admin', 'component').

provider

string

The authentication provider (e.g., 'wallet', 'accessKey').

fullName

string

The full name of the user.

walletOS

string

The operating system of the user's DID Wallet (e.g., 'ios', 'android', 'desktop', 'embed').

emailVerified

boolean

Indicates if the user's email is verified.

phoneVerified

boolean

Indicates if the user's phone is verified.

method

AuthMethod

The authentication method used for the current session ('loginToken', 'componentCall', 'signedToken', 'accessKey').

kyc

number

A bitmask representing KYC status. This is decoded into emailVerified and phoneVerified.

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

roles

string[]

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 403 Forbidden error is returned.

permissions

string[]

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 403 Forbidden error is returned.

kyc

KycMethod[]

An array of KYC methods ('email', 'phone'). The user must have all specified KYC methods verified to access the resource. If not, a 403 Forbidden error is returned.

methods

AuthMethod[]

An array of allowed authentication methods ('loginToken', 'componentCall', 'signedToken', 'accessKey'). The user's current authentication method must be one of the specified methods. If not, a 403 Forbidden error is returned.

getClient

Function

An optional function that returns an AuthService client. Defaults to AuthMiddleware.getServiceClient().

Authorization Checks#

The auth middleware performs checks in the following order, returning 403 Forbidden if any check fails:

  1. User DID: Verifies req.user.did or x-user-did header exists. If not, 401 Unauthorized is returned.
  2. Roles: If roles option is provided, checks if req.user.role is included in the specified roles.
  3. Permissions: If permissions option is provided, fetches permissions associated with req.user.role from Blocklet Server and checks if any required permission is present.
  4. KYC Status: If kyc option is provided, decodes req.user.kyc (a bitmask) and verifies if the required KYC methods (e.g., email, phone) are verified.
  5. Auth Method: If methods option is provided, checks if req.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.