Authentication and Token Refresh
NexusFlow's HTTP API uses Bearer access token authentication. The client first uses the account password to obtain the access token and refresh token, and subsequent requests only carry the access token; after the access token expires, the refresh token is exchanged for a new token pair.
This page only describes the authentication protocol and token management responsibilities that the client has. See API Conventions for common rules such as response encapsulation, status codes, and paging. See Authentication and Permissions for the order of determining roles and resource permissions.
First Distinguish Three Types of Credentials
| Credentials | Purpose | Possible Locations | Restrictions |
|---|---|---|---|
| access token | Call protected HTTP API; non-browser clients can also be used to job WebSocket handshakes | Authorization: Bearer ... request header | Cannot be used as a refresh token and should not be placed in a URL |
| refresh token | Request a new token pair after the access token expires | JSON request body of POST /api/token/refresh/ | Cannot directly call ordinary business interfaces |
| Job WebSocket Ticket | The browser connects to a real-time channel for a specified job | Job WebSocket ticket Query Parameters | One-time use, short-term validity, bound to users and jobs, cannot call HTTP API |
All three are sensitive information. Even if the access token is in JWT format, the client cannot interpret the user, organization, role or expiration time parsed by itself as an authorization conclusion. Whether the resource is accessible is always based on the current verification result of the server.
Log in Using Account and Password
Interface:
POST /api/token/
Content-Type: application/json
The request body has only two fields:
{
"username": "developer@example.com",
"password": "<password>"
}
| Field | Required | Description |
|---|---|---|
username | Yes | You can fill in the user name or the complete email address bound to the account; when using the email address, the field name is still username |
password | Yes | Current account password |
If the authentication is successful, the token field will be returned directly, and the message, code, and data encapsulation of the ordinary business interface will not be applied:
{
"refresh": "<refresh-token>",
"access": "<access-token>"
}
When logging in, the server will check the password, account activation status, account validity period and password validity period. The failure response belongs to the verification result of the token interface and should not be assumed to have exactly the same error structure as the ordinary business interface; account or password verification failures in the current implementation usually return 400 and JSON error details. The client SHOULD read the response body to display understandable information to the user, but MUST NOT log the submitted password or full response token.
Successful login only proves that the account can obtain the token, but does not mean that it has access to all workspaces, models, jobs or management interfaces. When you need to verify your identity and current user information, you can continue to call GET /api/users/me/ with the access token.
Carry Access Token
Protected HTTP requests use standard Bearer request headers:
Authorization: Bearer <access-token>
For example:
GET /api/users/me/
Authorization: Bearer <access-token>
Do not pass access tokens using:
- URL query parameters;
- Custom
tokenfield in request body; - Cookie, unless the server implements corresponding authentication and CSRF protection;
- Logs, abnormal text, monitoring tags or front-end buried points.
An access token can only be used in the platform environment that issued it. Even if the accounts in the test environment and production environment are the same, they cannot share tokens.
Refresh Token
Interface:
POST /api/token/refresh/
Content-Type: application/json
Request body:
{
"refresh": "<refresh-token>"
}
Refresh token rotation is currently enabled on the server. When the refresh is successful, a new access token and a new refresh token are returned:
{
"access": "<new-access-token>",
"refresh": "<new-refresh-token>"
}
The client must update the new token pair as a whole. To be compatible with server-side policy adjustments, successful responses should also be allowed to only provide new access; only when refresh does appear in the response, the saved refresh token will be replaced.
When refreshing, the server will recheck the refresh token, account activation status, account validity period and password validity period. When the token is invalid, the account status is invalid, or the password status is invalid, the current interface returns a verification error, and the client should stop automatic refresh and ask to log in again.
Don’T Write Down the Expiry Date
Login and refresh responses currently do not provide expires_in. Callers should not hard-code how long an access token or refresh token is valid, nor should they assume that a request is valid simply by parsing the JWT locally. It is recommended to handle it in the following way:
- Normally carry the current access token to call the API;
- When the protected interface explicitly returns
401, a controlled refresh is triggered; - Atomic replacement of the returned access token and optionally a new refresh token;
- Retry the original request using the new access token;
- When the refresh fails or is still
401after retrying, clear the local credentials and ask to log in again.
If the client reads the expiration field of JWT in order to reduce failed requests, this value can only be used as a scheduling prompt for early refresh and cannot replace server-side signature verification, account status and object permission verification.
The Current Rotation Is Not a Revocation
The current refresh process will issue new refresh tokens, but will not immediately blacklist old refresh tokens during rotation. Therefore:
- After receiving the new refresh token, you should still replace the old value as soon as possible, and you cannot continue to actively use the old value;
- "Refresh successful" cannot be understood to mean that the old refresh token has expired;
- When multiple processes or browser tabs share the same refresh token, multiple branch tokens may be generated;
- Security incident handling cannot rely on the refresh action to complete the revocation. The account or key handling process actually provided by the platform should be used.
Handling Concurrent Refreshes
Multiple requests may receive 401 at the same time due to expired access tokens. If each request is refreshed independently, it will cause duplicate logins, token overrides, and state races. It is recommended to use the "single refresh" mechanism for the same login context:
- The first
401creates a shared refresh job; - The remaining failed requests wait for the same refresh result and no new refresh requests are sent;
- After the refresh is successful, update the token pair at once, and then retry the waiting queue one by one;
- When the refresh fails, the credentials are cleared and the queue is terminated without looping and retrying.
The current browser-side Personal Center module uses a shared refresh promise, and the Simulation Workbench module uses a shared refresh job and failed request queue; both update local values when the response contains a new refresh token, and clean up the login state after a failed refresh. What is described here is the current client implementation, not the server that requires third parties to use a certain browser storage method.
The Python SDK will refresh and retry the original request after receiving 401 in a normal HTTP request; if the client still saves the account password, it will log in again when the refresh token is unavailable. The current SDK's authentication objects do not have concurrent refresh locks, nor do they promise that the same HTTP session can be safely shared by multiple threads. Multi-threaded or asynchronous wrappers should flush serially at the application layer, or use separate clients for each independent unit of work.
For requests that will produce external side effects, the business idempotent key and the server operation result should be combined to determine whether to retry. Authentication retry cannot be extended to unlimited business replay.
Logout and Token Revocation
Currently the only public authentication routes are:
POST /api/token/;POST /api/token/refresh/。
There are currently no public server-side logout, refresh token blacklist, or single-token revocation interfaces. "Exit" of the browser page will delete the local access token and refresh token and return to the login page. The token will not be revoked to the server. logout() is also not exposed by the Python SDK; closing the client only releases the local network session.
Therefore, after local exit, the token that has been leaked or copied by other processes will not become invalid immediately because the current page deletes it. The application should still clear its own saved credentials when exiting; if a leak occurs, the platform maintainer should be contacted immediately and handled according to the currently confirmed valid account disabling, signing key rotation or other security procedures. Do not assume that changing the password will necessarily revoke the existing token, nor make up a non-existent revocation request.
WebSocket Authentication
The job real-time channel supports two authentication methods, which are applicable to different clients.
Non-Browser Clients: Bearer Request Header
Clients that can set custom request headers for the WebSocket handshake can directly carry:
Authorization: Bearer <access-token>
The current Python SDK uses this method to connect job result channels. When 401 or 403 appears in the handshake, the SDK will try to refresh once if the refresh conditions are met; if it still fails the second time, the error will be handed over to the caller. Persistent 403 should usually be checked by permissions, job ownership or result status, rather than continuing to refresh.
Browser Client: One-Time Ticket
The browser's native WebSocket interface cannot set the Authorization request header, so first obtain the ticket through an authenticated HTTP request:
POST /api/jobs/{job_id}/websocket-ticket/
Authorization: Bearer <access-token>
The successful response is located in data of the ordinary business package:
| Field | Type | Description |
|---|---|---|
ticket | string | Randomly generated one-time connection ticket |
expires_in | integer | The remaining valid seconds of this ticket are based on each response and are not hard-coded. |
The server will also return Cache-Control: no-store. Establish a connection immediately after obtaining the ticket:
wss://nexusflow.example.com/ws/{job_id}?offset=0&ticket=<一次性票据>
Tickets have the following boundaries:
- Bind the user and job UUIDs that issued it;
- Atomic consumption during verification can only be used once;
- Valid only for the short time the response is given;
- Cannot be reused for another job, REST API or next reconnection;
- Each time you reconnect, you need to apply for a ticket again;
- Even if the ticket is valid, the server still checks whether the user is enabled and whether the current user has access to the job.
If the handshake contains both the Authorization request header and ticket, the current server will process the request header first and will not fall back to the ticket after the request header is invalid. The client should choose one method and not send both credentials at the same time.
Tickets can only appear in query parameters due to browser handshake limitations. Do not log the full WebSocket URL, and do not replace long-lived access tokens with URL parameters. For connection parameters, offset readback and handshake failure handling, see Real-Time Job Data Over WebSocket.
Common States of the Ticket Interface
| HTTP Status | Meaning |
|---|---|
401 | Does not carry a valid access token and should be processed according to the controlled refresh process |
403 | The identity is valid, but does not have permission to connect to the specified job; refreshing usually does not solve the problem |
404 | The specified job does not exist |
410 | The job record is still there, but the results have expired and the result connection can no longer be established. |
Distinguish Between 401, 403 and Token Interface Verification Errors
| Situation | Typical Response | Handle It Correctly |
|---|---|---|
| Login account, password or account status failed | The current token interface is usually 400, details are in the JSON response body | Correct credentials or contact the administrator to prevent automatic re-login |
| Refresh token or account status failed | The current refresh interface is usually 400, details are in the JSON response body | Clear local tokens and require re-login |
| Missing, corrupted or invalid access token for common protected interface | 401 | Refresh once and try again; if still fails, log in again |
| Authenticated but no resource or operation permissions | 403 | Check accounts, organizational roles, workspaces, and object permissions; do not refresh in a loop |
| Job result has expired | The ticket interface is 410 | Stop reconnecting and use exported data instead or recalculate |
Do not infer status from the error message text alone, and do not interpret all 403 as access token expiration. When recording troubleshooting information, the request path, HTTP status, non-sensitive error code in the response, occurrence time and request tracking information are retained, but Authorization, password, token response and full ticket URL are deleted.
Curl Minimal Example
The following example uses environment variables to save the platform address and short-lived credentials, and securely generates the JSON, read response with jq. https://nexusflow.example.com is a placeholder address; the actual environment should be replaced with the platform root address provided by the administrator, without appending /api/.
Log in and Read the Token
export NEXUSFLOW_BASE_URL="${NEXUSFLOW_BASE_URL:-https://nexusflow.example.com}"
export NEXUSFLOW_USERNAME="${NEXUSFLOW_USERNAME:-<用户名或邮箱>}"
export NEXUSFLOW_PASSWORD="${NEXUSFLOW_PASSWORD:-<由密钥管理器注入>}"
TOKEN_RESPONSE="$(
jq -n \
--arg username "$NEXUSFLOW_USERNAME" \
--arg password "$NEXUSFLOW_PASSWORD" \
'{username: $username, password: $password}' |
curl --fail-with-body --silent --show-error \
--request POST \
--header 'Content-Type: application/json' \
--data-binary @- \
"$NEXUSFLOW_BASE_URL/api/token/"
)"
export NEXUSFLOW_ACCESS_TOKEN="$(printf '%s' "$TOKEN_RESPONSE" | jq -er '.access')"
export NEXUSFLOW_REFRESH_TOKEN="$(printf '%s' "$TOKEN_RESPONSE" | jq -er '.refresh')"
unset NEXUSFLOW_PASSWORD TOKEN_RESPONSE
Do not print TOKEN_RESPONSE. On some operating systems, other processes under the same account may read environment variables; long-term services should instead use a key manager or a permission-controlled credential file and clean it up when the process exits.
Call Protected Interface
curl --fail-with-body --silent --show-error \
--header "Authorization: Bearer $NEXUSFLOW_ACCESS_TOKEN" \
"$NEXUSFLOW_BASE_URL/api/users/me/"
Refresh and Replace Token Pairs
REFRESH_RESPONSE="$(
jq -n \
--arg refresh "$NEXUSFLOW_REFRESH_TOKEN" \
'{refresh: $refresh}' |
curl --fail-with-body --silent --show-error \
--request POST \
--header 'Content-Type: application/json' \
--data-binary @- \
"$NEXUSFLOW_BASE_URL/api/token/refresh/"
)"
export NEXUSFLOW_ACCESS_TOKEN="$(printf '%s' "$REFRESH_RESPONSE" | jq -er '.access')"
NEW_REFRESH_TOKEN="$(printf '%s' "$REFRESH_RESPONSE" | jq -r '.refresh // empty')"
if [ -n "$NEW_REFRESH_TOKEN" ]; then
export NEXUSFLOW_REFRESH_TOKEN="$NEW_REFRESH_TOKEN"
fi
unset NEW_REFRESH_TOKEN REFRESH_RESPONSE
This command shows the field and rotation process, not a multi-process credential storage solution. Production services should update token pairs within a lock and complete atomic replacement using secure storage.
Security Integration Checklist
- The production environment uses HTTPS, the job channel uses WSS, and the certificate is verified normally;
- Use dedicated low-privilege accounts for scripts or external services and do not share administrator accounts;
- The password is only used for login requests, the access token is only placed in the Bearer request header, and the refresh token is only sent to the refresh interface;
- Not writing tokens, passwords, login responses, or ticket URLs into code, logs, screenshots, and error reports;
- Only one concurrent refresh job is allowed for the same login context, and the returned token pair is updated within the lock;
- Ordinary requests can be retried at most once after successful refresh, and
403will not enter the cycle refresh; - Local exit and server-side revocation are understood separately, and there is currently no public revocation interface;
- It does not rely on self-parsing JWT for permission judgment, and always relies on server endpoint verification;
- The browser applies for a new ticket for each WebSocket connection, and non-browser clients use the Bearer request header;
- Manage credentials separately across multiple environments to avoid bringing test tokens into the production environment.
Please read Real-Time Job Data Over WebSocket when continuing to access the job result channel.