User-delegated OAuth injection
User-delegated OAuth acts on behalf of a logged-on user, letting the sandbox query that user's own personal resources, such as DingTalk information and Feishu documents.
Overview
M2M (machine-to-machine) OAuth uses the identity of the application itself. Some scenarios require accessing the personal resources of a logged-on user on their behalf. Examples include querying their DingTalk information, reading and writing their Feishu documents, and accessing their Microsoft 365 files. These scenarios use user-delegated OAuth.
Read Credential injection overview first to understand the overall framework.
The biggest difference from M2M OAuth is that the user must grant authorization first. Therefore, in addition to injecting a token, user-delegated OAuth adds a step that guides the user through authorization.
Two ways to bind a user
When you create a sandbox, you must specify which user the sandbox represents. Provide one of the following:
|
Method |
Applies to |
What you provide |
|
JWT |
Your logon system can issue a user JWT (JSON Web Token) that Agent Identity trusts |
The valid JWT of the current logged-on user (the raw string, without the |
|
UserId |
You use a self-managed logon system and identify users by business user ID |
A stable and unique user ID, such as |
Agent Identity validates the JWT. Your backend submits the UserId after confirming the logged-on user, and the platform trusts the submitted value. The same user must always use the same UserId, and a UserId must not be reused by different users.
Prerequisites
Prepare the following in Agent Identity:
-
Create a Workload Identity and associate it with an available Resource Access Management (RAM) role.
-
If you use the JWT method, create an identity provider and associate it with the Workload Identity.
-
Grant the
agentidentitydata:GetResourceOAuth2Tokenpermission to the associated RAM role. -
Create an OAuth credential provider, and configure the authorization endpoint, token endpoint, client ID, client secret, and redirect URI.
-
Allow this Workload Identity to use the OAuth credential provider.
-
On the backend, prepare the API key that is used to create, update, and access sandboxes.
-
Confirm details such as the domain name, authentication header, and scopes of the target service.
All calls that create or update sandboxes are made from the backend and authenticated with this API key. A user JWT alone cannot be used to operate a sandbox. To learn how to create one, see Create an API Key.
Configure the sandbox
Assume that the logged-on user is Alice, the sandbox identity name is my-agent, the OAuth credential provider is dingtalk-provider, and the target is api.dingtalk.com. The backend first obtains Alice's JWT from the logon session (currentUserIdToken or current_user_id_token in the following examples). If you use the UserId method, use the business user ID that your backend has confirmed instead (currentUserId or current_user_id), and then create the sandbox:
Node.js
import { Sandbox } from "e2b";
const sandbox = await Sandbox.create("code-interpreter-v1", {
metadata: { "fc.sandbox.identity.name": "my-agent" },
network: {
allowOut: ["api.dingtalk.com"],
denyOut: ["0.0.0.0/0"],
rules: {
"@fc.sandbox.identity": [{
transform: { headers: {
"fc.sandbox.identity.oauth.userFederation.jwt": currentUserIdToken,
} },
}],
"api.dingtalk.com": [{
transform: { headers: {
"x-acs-dingtalk-access-token":
"${fc.sandbox.identity.oauth.userFederation:dingtalk-provider}",
} },
}],
},
},
});
Python
from e2b import Sandbox
sandbox = Sandbox.create(
template="code-interpreter-v1",
metadata={"fc.sandbox.identity.name": "my-agent"},
network={
"allow_out": ["api.dingtalk.com"],
"deny_out": ["0.0.0.0/0"],
"rules": {
"@fc.sandbox.identity": [{
"transform": {"headers": {
"fc.sandbox.identity.oauth.userFederation.jwt":
current_user_id_token
}}
}],
"api.dingtalk.com": [{
"transform": {"headers": {
"x-acs-dingtalk-access-token":
"${fc.sandbox.identity.oauth.userFederation:dingtalk-provider}"
}}
}]
},
},
)
Note the following points:
-
Place the user identity in the reserved key
@fc.sandbox.identity. This key is not a real domain name, is not injected into business requests, and must not be added toallowOut. -
The reference expression is
${fc.sandbox.identity.oauth.userFederation:<PROVIDER-NAME>}. -
If you use the UserId method, replace
...userFederation.jwtwith"fc.sandbox.identity.oauth.userFederation.userId": currentUserId("fc.sandbox.identity.oauth.userFederation.userId": current_user_idin Python). Everything else stays the same. Provide either a JWT or a UserId. If you provide both, the request fails.
If Alice has already granted authorization, the creation succeeds. If not, the creation returns an authorization-required error (see Handle the authorization-required error).
Verify credential injection
After the sandbox is created, request the target service from inside the sandbox without carrying the authentication header:
curl -i https://api.dingtalk.com/v1.0/contact/users/me
When the request goes out, the gateway injects Alice's DingTalk token.
Handle the authorization-required error
This step is specific to user-delegated OAuth. If Alice has not granted authorization, the create or update call returns HTTP 403 with the error code ResourceAuthorizationRequired. The details.authorizations field lists all OAuth credential providers that require authorization, together with their authorization URLs, in one response:
{
"code": "ResourceAuthorizationRequired",
"message": "User authorization is required.",
"details": {
"authorizations": [
{ "providerName": "dingtalk-provider",
"authorizationUrl": "https://auth.example.com/authorize/dingtalk" }
]
}
}
When you create a sandbox with the Python SDK, the authorization-required error is raised as an exception. The exception text is similar to 403: User authorization is required. The exception object keeps only the status code and message, but not code or details, so you cannot obtain authorizationUrl. If you need the URL, submit the create request as a raw HTTP request and read it from the response body:
import os
import httpx
API_URL = os.environ["E2B_API_URL"] # https://api.<REGION>.e2b.fc.aliyuncs.com
API_KEY = os.environ["E2B_API_KEY"]
# The create request is equivalent to the SDK example above. The timeout is in seconds.
create_payload = {
"templateID": "code-interpreter-v1",
"timeout": 300,
"metadata": {"fc.sandbox.identity.name": "my-agent"},
"network": {
"allowOut": ["api.dingtalk.com"],
"denyOut": ["0.0.0.0/0"],
"rules": {
"@fc.sandbox.identity": [{
"transform": {"headers": {
"fc.sandbox.identity.oauth.userFederation.jwt":
current_user_id_token
}}
}],
"api.dingtalk.com": [{
"transform": {"headers": {
"x-acs-dingtalk-access-token":
"${fc.sandbox.identity.oauth.userFederation:dingtalk-provider}"
}}
}]
}
}
}
resp = httpx.post(f"{API_URL}/sandboxes",
headers={"X-API-Key": API_KEY},
json=create_payload)
body = resp.json()
if resp.status_code == 403 and body.get("code") == "ResourceAuthorizationRequired":
authorizations = body["details"]["authorizations"]
# Return authorizations to the logged-on user who made the request, and guide them to complete authorization.
# Do not write the authorizationUrl values to logs.
After the logged-on user completes all authorizations, retry with the same create_payload to create the sandbox. httpx is a dependency of the E2B Python SDK, so you do not need to install it separately.
The raw HTTP approach applies to the E2B Python SDK. Neither version 2.31.0, which the installation command in this collection pins, nor version 2.63.0 keeps details. If a later SDK version exposes structured authorization information, you can read the URL directly from the exception object.
To handle the error, follow these steps:
-
The backend identifies the error and shows the
authorizationUrlto Alice. Use the URL returned in the response instead of constructing one. -
Alice opens the URL and completes third-party logon and authorization.
-
After all authorizations are completed, the backend resubmits the original create or update request.
-
The platform can then obtain the token, and the sandbox is created or updated.
No sandbox is created when the authorization-required error is returned. For an update, none of the changes take effect. Completing only some of the authorizations does not apply part of the configuration. Retry only after all authorizations are completed.
Session binding (state and callbackUrl)
If session binding is enabled in the Workload Identity, two additional fields are required in the create request. The backend uses them to verify, at callback time, that the same user initiated the request:
Node.js
import { randomBytes } from "node:crypto";
import { Sandbox } from "e2b";
const authorizationState = randomBytes(32).toString("hex");
const callbackUrl = "https://customer.example.com/oauth/callback";
const sandbox = await Sandbox.create("code-interpreter-v1", {
metadata: { "fc.sandbox.identity.name": "my-agent" },
network: {
allowOut: ["api.dingtalk.com"],
denyOut: ["0.0.0.0/0"],
rules: {
"@fc.sandbox.identity": [{
transform: { headers: {
"fc.sandbox.identity.oauth.userFederation.jwt": currentUserIdToken,
"fc.sandbox.identity.oauth.userFederation.state": authorizationState,
"fc.sandbox.identity.oauth.userFederation.callbackUrl": callbackUrl,
} },
}],
"api.dingtalk.com": [{ transform: { headers: {
"x-acs-dingtalk-access-token":
"${fc.sandbox.identity.oauth.userFederation:dingtalk-provider}",
} } }],
},
},
});
Python
import secrets
from e2b import Sandbox
authorization_state = secrets.token_hex(32)
callback_url = "https://customer.example.com/oauth/callback"
sandbox = Sandbox.create(
template="code-interpreter-v1",
metadata={"fc.sandbox.identity.name": "my-agent"},
network={
"allow_out": ["api.dingtalk.com"],
"deny_out": ["0.0.0.0/0"],
"rules": {
"@fc.sandbox.identity": [{
"transform": {"headers": {
"fc.sandbox.identity.oauth.userFederation.jwt":
current_user_id_token,
"fc.sandbox.identity.oauth.userFederation.state":
authorization_state,
"fc.sandbox.identity.oauth.userFederation.callbackUrl":
callback_url
}}
}],
"api.dingtalk.com": [{"transform": {"headers": {
"x-acs-dingtalk-access-token":
"${fc.sandbox.identity.oauth.userFederation:dingtalk-provider}"
}}}]
},
},
)
Before you create the sandbox, save the mapping between authorizationState (which is authorization_state in Python) and the current logon session in backend storage, so that the callback can be verified.
When session binding is enabled, one more step is added to the authorization flow. When the authorization callback reaches the backend callbackUrl, the backend verifies the state and the current logged-on user. The backend then uses the session_uri returned in the callback to call CompleteResourceTokenAuth before retrying the original request. The platform only passes the state through unchanged, so generate and verify it in the backend.
If session binding is not enabled, you do not need to handle state or callbackUrl. After the logged-on user completes authorization in the Agent Identity flow, the backend can retry the original request directly.
Update the configuration and switch users
Update injection rules or switch users while the sandbox is running. For more information, see Update network configuration. To switch users, submit a new JWT or UserId in the reserved key.
Rules for updating the user identity:
-
Provide either a JWT or a UserId. If both are omitted, the current user identity is retained.
-
Each submitted JWT is re-validated. When you switch users, the new user does not need to be the same person as the original user.
-
Only running sandboxes support updates. A paused sandbox must be resumed first.
The JWT and UserId update rules apply only to user-delegated OAuth.
Limits
For the common limits and security requirements, see Credential usage limits.