Get tokens and API keys
Sign in a user when your app should act with that user's permissions. Create an API key for a server, job, or integration that acts as the key's owner. This guide shows the supported SDK calls and the HTTP request fields behind each flow.
Before you start#
- Use the URL of the site where the account exists. The HTTP paths below
are relative to
TARUVI_SITE_URL. - Have an existing account and its sign-in details. Creating an API key also requires organization access to that site.
- Install and configure the JavaScript SDK or Python SDK if you choose an SDK tab.
Use HTTPS outside local development. The uppercase values in request and response examples are placeholders, not real credentials.
Sign in a user#
- JavaScript SDK
- Python SDK
- Refine
- REST
Browser apps use hosted sign-in, so your app does not collect the user's password. Create the client on the page users return to:
import {Auth, Client} from '@taruvi/sdk';
const client = new Client({
apiUrl: 'https://YOUR_SITE_HOST',
appSlug: 'APP_SLUG',
});
export const auth = new Auth(client);
export function signIn(): void {
auth.login(window.location.origin);
}
Replace YOUR_SITE_HOST and APP_SLUG with your site host and app slug. Call
signIn() from your sign-in button. It opens /accounts/login/ with the
absolute return URL in redirect_to.
After sign-in, TaruviBase redirects back with session_token in the URL
fragment. When this module loads again, the client captures it and sends
X-Session-Token on later API calls. Check the session with
await auth.isUserAuthenticated(); use auth.getSessionToken() only when you
need to pass the user's session to your own backend.
For custom return pages, server rendering, or mobile clients, follow JavaScript authentication. The hosted redirect helpers require a browser.
For an interactive script, sign in with the account's email and password.
signInWithPassword() returns a new client, authenticated with a JWT;
it does not change the original client.
import os
from getpass import getpass
from taruvi import Client
with Client(
os.environ["TARUVI_SITE_URL"],
os.environ["TARUVI_APP_SLUG"],
mode="sync",
api_key=None,
jwt=None,
session_token=None,
) as client:
with client.auth.signInWithPassword(
email=input("Email: "),
password=getpass("Password: "),
) as user_client:
current_user = user_client.auth.get_current_user()
print(current_user["data"]["username"])
Set TARUVI_SITE_URL and TARUVI_APP_SLUG before running the script. The
explicit empty credential options prevent a service credential from the
environment being used for this sign-in.
The SDK sends email and password to POST /_allauth/app/v1/auth/login,
then uses the returned meta.access_token as a bearer JWT. For the async
client and existing-token options, see
Python authentication.
Use an API key for unattended jobs instead of storing a user's password.
Configure authProvider(taruvi) with the browser client and protected routes
from Refine setup. Use
useLogin on your sign-in route to open TaruviBase hosted sign-in.
import {useLogin} from '@refinedev/core';
import type {LoginParams} from '@taruvi/refine-providers';
const {mutate: login} = useLogin<LoginParams>();
// Call from an event handler.
login({callbackUrl: window.location.origin});
After the hosted page returns, the SDK captures the session from the URL.
The protected route's <Authenticated> check validates it before rendering
your app. Keep the callback on your own app's origin.
Send a JSON body to POST /_allauth/app/v1/auth/login on the target site,
with Content-Type: application/json.
{
"email": "USER_EMAIL",
"password": "USER_PASSWORD"
}
email— The existing account's email address.password— That account's password.X-Session-Token— Omit this header when starting a new sign-in. If the authentication flow returns a session token, preserve it and send it on subsequent authentication requests.
A completed sign-in returns HTTP 200 with meta.is_authenticated: true.
Read these fields from the response:
| Field | Use |
|---|---|
meta.session_token, when returned | Send as X-Session-Token to act as this user. |
meta.access_token | Send as Authorization: Bearer ACCESS_TOKEN if your integration uses JWTs. |
meta.refresh_token | Keep for JWT refresh; do not use it as a bearer access token. |
meta.expires_in | Access-token lifetime, in seconds. |
data.user | The signed-in user's details. |
A session token can also identify an unfinished authentication flow.
Do not treat possession of one as proof of sign-in: inspect
meta.is_authenticated and any pending entries in data.flows. If your
client does not implement the required flow, use hosted sign-in instead.
Create an API key#
An API key is created for an already signed-in user with organization access to the site. An ordinary site-user sign-in does not grant permission to create keys. The key inherits its creator's permissions and has no independent per-key scopes. Because its creator has organization access, requests made with the key skip app roles and Database row policies: use keys for trusted server jobs, and forward a user's session token to act for that user.
- REST
- Console
Send a JSON body to POST /api/users/token/, using your existing session
token or JWT access token to authenticate. Set Content-Type: application/json
and one of these headers:
X-Session-Token: SESSION_TOKENAuthorization: Bearer ACCESS_TOKEN
{
"name": "TOKEN_NAME",
"expiry": "EXPIRY_ISO_8601"
}
name— Required label, up to 50 characters. Choose one that identifies the integration using the key.expiry— Required. ReplaceEXPIRY_ISO_8601with a future timestamp in ISO 8601 format. JSONnullcreates a key with no expiry; prefer a finite expiry so you can rotate the credential.
HTTP 201 confirms creation. Copy data.token from the response and
store it securely; subsequent list requests do not return the plaintext key.
The response also includes data.id, data.name, data.created, and
data.expiry.
- Open the target site in the Console.
- Go to Settings → API Tokens → Create Token. From an app, you can also use Settings → Connect → Generate API Key.
- Enter a name and choose an expiration, then select Create Token.
- Copy the key while it is displayed and store it securely.
For rotation and revocation, follow Issue API tokens.
Use the created API key with JavaScript server authentication or Python API-key authentication. Keep keys out of browser code, mobile bundles, and public build variables.
Use JWTs#
The Python sign-in flow and the headless REST flow above can return a JWT access token. If your integration uses the separate JWT endpoints, the request fields and response names are different:
Obtain a token pair#
Send POST /api/cloud/auth/jwt/token/ with
Content-Type: application/json and this JSON body:
{
"username": "USERNAME",
"password": "USER_PASSWORD"
}
Use the account's username, not the email field used by headless
sign-in. A successful response is HTTP 200 with top-level access and
refresh strings. It does not use meta.access_token and does not create a
headless session token. The /api/cloud/ prefix is part of this route;
obtaining a JWT does not grant the user additional permissions.
Refresh an access token#
Send POST /api/cloud/auth/jwt/token/refresh/ with
Content-Type: application/json and the refresh token in the body:
{
"refresh": "REFRESH_TOKEN"
}
Read the new access token from the response's access field. If the
response also contains refresh, replace the stored refresh token with
that value; token rotation can invalidate the old one. If refresh is
rejected, sign in again.
Pass the JWT to the Python SDK with jwt= or
signInWithToken(token, token_type="jwt"). The JavaScript SDK uses session
tokens or explicit server API-key mode; its token option is a session
token, not a bearer JWT.
Check the credential#
Use the same authenticated client or provider as the application request you
want to verify. taruvi is your configured JavaScript client; client is the
configured synchronous Python client.
- JavaScript SDK
- Python SDK
- Refine
- REST
import {User} from '@taruvi/sdk';
const currentUser = await new User(taruvi).getUser('me');
console.log(currentUser.data.username);
me reads the credential owner. Use the signed-in user's session or a server
API key.
current_user = client.auth.get_current_user()
print(current_user["data"]["username"])
Use userDataProvider(taruvi) registered as user inside the authenticated
Refine app:
import {useOne} from '@refinedev/core';
import type {UserData} from '@taruvi/sdk';
useOne<UserData>({
dataProviderName: 'user', resource: 'users', id: 'me',
});
After the hook's query.isSuccess, check result.username against the
intended credential owner.
Send GET /api/users/me/ with the header for your credential:
- Session token:
X-Session-Token: SESSION_TOKEN - API key:
Authorization: Api-Key TARUVI_API_KEY - JWT access token:
Authorization: Bearer ACCESS_TOKEN
The SDK and REST responses contain the caller under data; Refine unwraps
it into result. Confirm that it is
the user you intended before making application requests. A valid credential
does not guarantee access to every resource: the caller's roles and policies
still apply.
Next, read and write records or check access policies.