A Token for the Browser Enrollment SDK
The backend route behind the getAccessToken option of the Unified Enrollment SDK v2: it answers only a signed-in user who owns the subaccount, with a fresh token from your SDK client.
For: developers
The Unified Enrollment SDK v2 in your page asks your backend for a token through its getAccessToken option. This recipe is that backend route, GET /your-backend/astrada-sdk-token?subaccountId=.... It:
- answers only a signed-in user, and only for a subaccount that user owns in your database;
- mints a new token each time with your SDK client, the separate client id and secret Astrada gives you for the browser;
- refuses to hand out a token that carries a scope outside the list at the top of the code;
- answers the token as plain text, with
Cache-Control: no-store.
Never hand the browser a token of your backend API client: that token carries every scope your backend holds, writes included.
Before you start
- Two clients: your backend API client, and your SDK client for the browser. The backend client needs no scope for this route; the SDK client needs only the browser's scopes, listed at the top of the code. SDK Credentials explains the difference. A sandbox account you signed up for yourself can have one client for both: read Self sign-up sandbox accounts before you run the code.
- Your login, and a table of which user owns which subaccount.
- A page that opens SDK v2 with a
getAccessTokenfunction that calls this route: Options.
The token is not tied to one subaccountFor its few minutes, the token works on every subaccount of your account, within the SDK client's scopes. The check that the user owns the subaccount happens here, on your server, and a user who copies the token can call the API with it until it expires. When one subaccount must be the limit, look at enrollment links: you make each link for one subaccount, and Astrada hosts its page.
The code
The route
Drop the two banking scopes from the list if you do not offer bank sign-in, and ask Astrada to remove any scope your SDK client holds beyond the list. Never add banking:admin or webhooks:write.
A new token is minted on every call: the browser SDK asks again after a 401, and a cached token would be the one Astrada just refused. If the SDK client holds a scope outside the list, the SDK raises an error before anything is handed out, and the route answers 502.
/**
* The scopes the browser calls need: card enrollment and bank sign-in. Drop the two banking scopes
* if you do not offer bank sign-in, and ask Astrada to remove any scope your SDK client holds
* beyond this list. Never banking:admin or webhooks:write.
*/
export const ALLOWED_SCOPES = [
'subaccounts:read',
'card-subscriptions:read',
'card-subscriptions:write',
'card-verifications:read',
'card-verifications:write',
'enrollment-methods:write',
'banking:read',
'banking:write',
] as const;
/** Your login and your table of who owns which subaccount. */
export interface Sessions {
/** The signed-in user of this request, or undefined. */
userOf(req: IncomingMessage): Promise<string | undefined>;
/** True when your database says this user may use this subaccount. */
owns(userId: string, subaccountId: string): Promise<boolean>;
}
/** The SDK client's credentials, and the scopes its token may carry (undefined: not checked). */
export interface SdkClient {
clientId: string;
clientSecret: string;
allowedScopes: readonly string[] | undefined;
}ALLOWED_SCOPES: Sequence[str] = (
"subaccounts:read",
"card-subscriptions:read",
"card-subscriptions:write",
"card-verifications:read",
"card-verifications:write",
"enrollment-methods:write",
"banking:read",
"banking:write",
)
"""The scopes the browser calls need: card enrollment and bank sign-in. Drop the two banking
scopes if you do not offer bank sign-in, and ask Astrada to remove any scope your SDK client holds
beyond this list. Never banking:admin or webhooks:write."""
class Sessions(Protocol):
"""Your login and your table of who owns which subaccount."""
def user_of(self, request: BaseHTTPRequestHandler) -> Optional[str]:
"""The signed-in user of this request, or None."""
def owns(self, user_id: str, subaccount_id: str) -> bool:
"""True when your database says this user may use this subaccount."""
@dataclass
class SdkClient:
"""The SDK client's credentials, and the scopes its token may carry (None: not checked)."""
client_id: str
client_secret: str
allowed_scopes: Optional[Sequence[str]]/**
* The scopes the browser calls need: card enrollment and bank sign-in. Drop the two banking scopes
* if you do not offer bank sign-in, and ask Astrada to remove any scope your SDK client holds
* beyond this list. Never banking:admin or webhooks:write.
*/
public static final List<String> ALLOWED_SCOPES = Collections.unmodifiableList(Arrays.asList(
"subaccounts:read",
"card-subscriptions:read",
"card-subscriptions:write",
"card-verifications:read",
"card-verifications:write",
"enrollment-methods:write",
"banking:read",
"banking:write"));
/** Your login and your table of who owns which subaccount. */
public interface Sessions {
/** The signed-in user of this request, or null. */
String userOf(HttpExchange exchange);
/** True when your database says this user may use this subaccount. */
boolean owns(String userId, String subaccountId);
}
/** The SDK client's credentials, and the scopes its token may carry (null: not checked). */
public static final class SdkClient {
public final String clientId;
public final String clientSecret;
public final List<String> allowedScopes;
public SdkClient(String clientId, String clientSecret, List<String> allowedScopes) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.allowedScopes = allowedScopes;
}
}The route itself:
/** The token route, `GET /your-backend/astrada-sdk-token?subaccountId=...`. */
export function sdkTokenRoute(astrada: Astrada, sdkClient: SdkClient, sessions: Sessions) {
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (req.method !== 'GET' || url.pathname !== '/your-backend/astrada-sdk-token') {
res.writeHead(404).end();
return;
}
try {
const userId = await sessions.userOf(req);
if (userId === undefined) {
res.writeHead(401).end();
return;
}
const subaccountId = url.searchParams.get('subaccountId');
if (!subaccountId || !(await sessions.owns(userId, subaccountId))) {
res.writeHead(403).end();
return;
}
// A new token on every call: the browser SDK asks again after a 401, and a cached token
// would be the one Astrada just refused.
const token = await astrada.mintSdkAccessToken(sdkClient);
res.writeHead(200, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' }).end(token);
} catch (error) {
if (error instanceof UnexpectedScopesError) {
// The SDK client holds a scope the browser must not get. Nothing was handed out.
console.error('SDK client has extra scopes; ask Astrada to remove them:', error.message);
} else {
console.error('could not mint the SDK token', error);
}
// Once an answer has started (the token was being written when the browser went away), a
// second one would throw: close the connection instead.
if (res.headersSent) res.destroy();
else res.writeHead(502).end();
}
};
}def sdk_token_route(
client: astrada.Astrada, sdk_client: SdkClient, sessions: Sessions
) -> Type[BaseHTTPRequestHandler]:
"""The token route, ``GET /your-backend/astrada-sdk-token?subaccountId=...``."""
class SdkTokenRoute(BaseHTTPRequestHandler):
def do_GET(self) -> None:
self._answered = False
url = urlsplit(self.path)
if url.path != "/your-backend/astrada-sdk-token":
self._answer(404)
return
try:
user_id = sessions.user_of(self)
if user_id is None:
self._answer(401)
return
subaccount_id = (parse_qs(url.query).get("subaccountId") or [""])[0]
if not subaccount_id or not sessions.owns(user_id, subaccount_id):
self._answer(403)
return
# A new token on every call: the browser SDK asks again after a 401, and a cached
# token would be the one Astrada just refused.
token = client.mint_sdk_access_token(
sdk_client.client_id, sdk_client.client_secret, sdk_client.allowed_scopes)
self._answer(200, token)
except astrada.UnexpectedScopesError as error:
# The SDK client holds a scope the browser must not get. Nothing was handed out.
print("SDK client has extra scopes; ask Astrada to remove them:", error)
self._answer_unless_sent(502)
except Exception as error:
print("could not mint the SDK token", type(error).__name__, error)
self._answer_unless_sent(502)
def _answer_unless_sent(self, status: int) -> None:
# Once an answer has started (the token was being written when the browser went
# away), a second one would fail too: close the connection instead.
if self._answered:
self.close_connection = True
else:
self._answer(status)
_answered = False
def _answer(self, status: int, text: str = "") -> None:
data = text.encode("utf-8")
self._answered = True
self.send_response(status)
if text:
self.send_header("Content-Type", "text/plain")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format: str, *args: Any) -> None:
return None # quiet; log the way your app does
return SdkTokenRoute/** The token route, {@code GET /your-backend/astrada-sdk-token?subaccountId=...}. */
public static HttpHandler sdkTokenRoute(ApiClient client, SdkClient sdkClient, Sessions sessions) {
return exchange -> {
if (!"GET".equals(exchange.getRequestMethod())
|| !"/your-backend/astrada-sdk-token".equals(exchange.getRequestURI().getPath())) {
answer(exchange, 404, null);
return;
}
try {
String userId = sessions.userOf(exchange);
if (userId == null) {
answer(exchange, 401, null);
return;
}
String subaccountId = queryParameter(exchange.getRequestURI().getRawQuery(), "subaccountId");
if (subaccountId == null || subaccountId.isEmpty() || !sessions.owns(userId, subaccountId)) {
answer(exchange, 403, null);
return;
}
// A new token on every call: the browser SDK asks again after a 401, and a cached token
// would be the one Astrada just refused.
String token = client.mintSdkAccessToken(sdkClient.clientId, sdkClient.clientSecret, sdkClient.allowedScopes);
answer(exchange, 200, token);
} catch (UnexpectedScopesException e) {
// The SDK client holds a scope the browser must not get. Nothing was handed out.
System.err.println("SDK client has extra scopes; ask Astrada to remove them: " + e.getExtraScopes());
answerUnlessSent(exchange, 502);
} catch (IOException | RuntimeException e) {
System.err.println("could not mint the SDK token: " + e.getClass().getSimpleName() + " " + e.getMessage());
answerUnlessSent(exchange, 502);
}
};
}
/**
* Answers {@code status}, unless an answer has already started (writing the token failed, for
* example because the browser went away): a second answer would fail too, so just close.
*/
private static void answerUnlessSent(HttpExchange exchange, int status) throws IOException {
if (exchange.getResponseCode() == -1) {
answer(exchange, status, null);
} else {
exchange.close();
}
}
private static void answer(HttpExchange exchange, int status, String text) throws IOException {
if (text == null) {
exchange.sendResponseHeaders(status, -1);
} else {
byte[] data = text.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain");
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.sendResponseHeaders(status, data.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(data);
}
}
exchange.close();
}
private static String queryParameter(String rawQuery, String name) {
if (rawQuery == null) {
return null;
}
for (String pair : rawQuery.split("&")) {
int equals = pair.indexOf('=');
if (equals > 0 && name.equals(URLDecoder.decode(pair.substring(0, equals), StandardCharsets.UTF_8))) {
return URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8);
}
}
return null;
}Self sign-up sandbox accounts
A sandbox account you signed up for yourself can have one client for both uses, so its tokens carry more scopes than the list. There, leave the scope check out. Never do this in production.
/** The scopes to check: all of ALLOWED_SCOPES, except on a self sign-up sandbox account. */
export function allowedScopesFor(environment: 'sandbox' | 'production', selfSignUpSandbox: boolean): readonly string[] | undefined {
if (environment === 'sandbox' && selfSignUpSandbox) return undefined;
return ALLOWED_SCOPES;
}def allowed_scopes_for(environment: str, self_sign_up_sandbox: bool) -> Optional[Sequence[str]]:
"""The scopes to check: all of ALLOWED_SCOPES, except on a self sign-up sandbox account."""
if environment == "sandbox" and self_sign_up_sandbox:
return None
return ALLOWED_SCOPES/** The scopes to check: all of ALLOWED_SCOPES, except on a self sign-up sandbox account. */
public static List<String> allowedScopesFor(String environment, boolean selfSignUpSandbox) {
if ("sandbox".equals(environment) && selfSignUpSandbox) {
return null;
}
return ALLOWED_SCOPES;
}Whole example files: TypeScript, Python, Java.
What to expect
- A signed-in user who owns the subaccount gets
200with the token as plain text. - No signed-in user gets
401; a subaccount the user does not own, or nosubaccountId, gets403. - Until you replace the demo's login with yours, the route refuses everyone.
Read more
- A token for the browser enrollment SDK: the SDK call this route makes.
- Authentication: API and SDK credentials.
- Going to Production: what changes for SDK v2 in production.
Updated 28 minutes ago
