Skip to main content

Authentication

This page is for the practitioner who needs to get an authenticated client running with the right token flow.

Pick a provider​

ScenarioProviderNeedsRefresh
Notebook / desktop CLI / interactive userAuthorizationCodeTokenProviderBrowser, SAS Logon redirect_uriIn-memory
Service-to-service, CI, scheduled jobClientCredentialsTokenProviderclient_id, client_secretIn-memory
Already have a bearer token from another systemStaticTokenProviderThe raw tokenNone
Controlled dev/test (not recommended for prod)UsernamePasswordTokenProviderUsername + password + client idIn-memory

All four providers implement the same TokenProvider protocol, with synchronous and async token access. Pick by scenario, not by feature parity.

Start with authorization code + PKCE​

This is the first auth flow new users should try because it matches an interactive human login:

from sasvi import SVIClient
from sasvi.auth import AuthorizationCodeTokenProvider

svi = SVIClient(
base_url="https://viya.example.com",
auth=AuthorizationCodeTokenProvider(open_browser=True),
)

svi.verify_connection()

SVIClient(...) construction is side-effect-free. The browser flow starts on the first authenticated request or when you call svi.verify_connection(). If your environment uses self-signed certificates, set verify_ssl=False on SVIClient(...) so auth and later API calls use the same TLS setting.

Cleanup note:

  • with SVIClient(...) as svi closes synchronous resources
  • async with SVIClient(...) as svi or await svi.close_async() performs full async cleanup
  • The OAuth providers build their own SAS Logon HTTP clients on the first token request, and have close() and close_async(). SVIClient closes a provider it built from the environment or copied while binding it, after the service clients and svi.custom. A provider you construct and that the client uses unchanged (svi.auth is provider) stays yours: close it yourself, or share it across several clients and close it once at the end.

The user authenticates as themselves, and there is no separate token bootstrap step to explain first, which is why exploratory scripts and notebooks start here.

Where the code prompt runs​

After you sign in, SAS Logon shows an authorization code (or redirects to a callback URL). The default prompt asks for it without echoing it. It works in a terminal and in a running Jupyter notebook cell, where it shows a masked input box in the cell output. Paste either the code or the full callback URL.

Anywhere else the default prompt raises AuthConfigurationError instead of waiting on standard input. That includes a server, a scheduled job, and a notebook thread or task that asks for a token after its cell has finished. In a notebook, sign in from a cell first, for example with svi.verify_connection(), and start background work afterwards.

Some notebook front ends cannot answer input requests. There the prompt prints the authorization URL and then raises AuthConfigurationError, and the provider keeps that login pending. Sign in at the printed URL and finish the login in the next cell:

svi.auth.authorize(code="<code or callback URL>")

Call it on svi.auth, not on the provider you constructed. SVIClient copies a provider to give it the base URL, and only that copy holds the PKCE verifier for the printed URL. The code is single-use, so the one left in the cell is spent once the call returns.

An application with its own way to ask the user, such as a dialog or a web form, passes prompt_for_code=. The callable receives the authorization URL and returns the code or the callback URL. A callable that calls input() or getpass.getpass() works only where the default prompt already works.

A run that nobody attends, such as nbconvert, papermill or a scheduled job, should use ClientCredentialsTokenProvider instead.

Follow with username and password​

Use this next in controlled development or smoke-test environments:

from sasvi import SVIClient
from sasvi.auth import UsernamePasswordTokenProvider

svi = SVIClient(
base_url="https://viya.example.com",
auth=UsernamePasswordTokenProvider(
username="analyst",
password="secret",
),
)

Pass client_id= and client_secret= when your SAS Logon client is not the default sas.cli.

How the refresh-token providers renew​

AuthorizationCodeTokenProvider and UsernamePasswordTokenProvider both keep a refresh token and use it before repeating their original grant. Repeating the grant means a fresh interactive login for the authorization-code provider, and another password grant for the username and password provider. They tell the two failure cases apart: when SAS Logon rejects the refresh token they discard it and repeat the grant, and when SAS Logon is merely unreachable they keep the refresh token and raise the transport failure, so a network blip no longer costs you a fresh login.

When SAS Logon is down​

A token request that SAS Logon answers with 408, 429 or a 5xx raises AuthServiceUnavailableError. It is both an AuthConfigurationError and a TransientError, so existing handlers still catch it and retry logic keyed on TransientError fires. It carries status_code and retry_after (seconds, from the Retry-After header when SAS Logon sent one), and never the response body. 400, 401 and 403 stay plain AuthConfigurationError: the credentials or the grant were rejected.

Before raising, the SDK resends a client-credentials or password grant up to two times, with jitter, honouring Retry-After, inside the calling request's request_deadline_seconds. An authorization-code exchange and a refresh-token grant are sent once, because the code is single-use and a refresh token can rotate when it is used. After an outage both providers keep their refresh token.

from sasvi.errors import AuthServiceUnavailableError

try:
svi.verify_connection()
except AuthServiceUnavailableError as exc:
wait = exc.retry_after or 5.0 # SAS Logon is restarting; the credentials are fine

Reuse the same client shape​

The rest of the docs assume you already have an authenticated svi client built with one of the providers on this page. Call svi.verify_connection() if you want an explicit connectivity check up front. Otherwise the auth flow starts lazily on the first authenticated request.

Use a static bearer token​

Choose this when another system already acquires the token:

from sasvi import SVIClient
from sasvi.auth import StaticTokenProvider

svi = SVIClient(
base_url="https://viya.example.com",
auth=StaticTokenProvider("access-token"),
)

StaticTokenProvider never refreshes. When the token expires, build a new client.

Use OAuth client credentials​

Choose this when you have a service account and want token renewal handled for you:

from sasvi import SVIClient
from sasvi.auth import ClientCredentialsTokenProvider

svi = SVIClient(
base_url="https://viya.example.com",
auth=ClientCredentialsTokenProvider(
client_id="sdk-client",
client_secret="sdk-secret",
),
)

This provider exchanges the client id and secret for a SAS Logon token and caches it in memory. There is no refresh-token grant; when the cached token expires it requests a new one with the same credentials.

Inspect what a provider holds​

The three OAuth providers have token_state(). It makes no request and returns a frozen TokenState with expires_at, the absolute UTC time at which the provider stops using its access token (None before the first token), and has_refresh_token. It carries no token value, so it is safe to log:

state = svi.auth.token_state()
print(state.expires_at, state.has_refresh_token)

expires_at already has the provider's expiry_skew_seconds (30 by default) subtracted. To tell whether a caught exception is a TLS failure, use sasvi.errors.is_tls_failure(exc), which walks the whole exception chain.

Error reporters that capture local variables​

repr() and to_dict() of every provider hide its secrets. During a token request, the password, the client secret, the authorization code and the PKCE verifier also render as '<redacted>' in the SDK's own frames. HTTPX's frames further down still hold the encoded form body for the moment the request is in flight. Sentry's default settings, rich.traceback(show_locals=True) and traceback.TracebackException(capture_locals=True) record those frames when a token request fails. Turn off local-variable capture in such a reporter, or scrub sasvi.auth and httpx2 frames, wherever the process holds a password or client secret.

Reuse the sasvi auth login cache in a long-running process​

sasvi auth login caches one access token on disk and no refresh token, so the cached login lasts one access-token lifetime. sasvi.cli.cached_token_provider() returns a TokenProvider that reads the cache again when its token has expired, so a second sasvi auth login takes effect without a restart:

from sasvi import SVIClient
from sasvi.cli import cached_token_provider

svi = SVIClient(
base_url="https://viya.example.com",
auth=cached_token_provider(base_url="https://viya.example.com"),
)

When the cache holds no unexpired token, a request raises AuthConfigurationError("cached login expired; run sasvi auth login"). The provider refuses a token that was issued for another origin. It needs that origin up front: pass base_url=, or set SASVI_BASE_URL before you create it. With neither, cached_token_provider() raises AuthConfigurationError. It reads the default token.json. A login made for a profile is cached in that profile's own file, so pass that file as the first argument: cached_token_provider(token_path_for("prod"), base_url=...), with token_path_for from sasvi.cli.token_store. sasvi.cli.maybe_inject_cached_token() is the one-shot form for a short script: it sets SASVI_ACCESS_TOKEN once and never renews it. See the CLI guide.

Environment resolution order​

Use this only when your runtime environment already injects the relevant SASVI_* variables. It is a supporting constructor option, not the primary beginner onboarding path in these docs.

SVIClient.from_env() resolves auth in this order, and stops at the first match:

  1. SASVI_ACCESS_TOKEN builds a StaticTokenProvider
  2. SASVI_CLIENT_ID + SASVI_CLIENT_SECRET build a ClientCredentialsTokenProvider
  3. SASVI_USERNAME + SASVI_PASSWORD build a UsernamePasswordTokenProvider

When none of the three matches, from_env() raises AuthConfigurationError.

SASVI_BASE_URL is always required unless you pass base_url= explicitly.

Cases 2 and 3 build an OAuth provider, and that provider reads four more variables. The last two also configure the client itself, and SASVI_TIMEOUT takes a different default on each side.

VariableEffectDefault
SASVI_TOKEN_URLFull token endpoint URL, for when SAS Logon is not on the tenant host. The SDK trims it back to the SAS Logon service root and drops any query string, so the token request always goes to <root>/oauth/token on that URL's host.<SASVI_BASE_URL>/SASLogon
SASVI_SCOPESRequested scopes, separated by commas or spacesNo scopes requested
SASVI_TIMEOUTTimeout in seconds10.0 on the token call, 30.0 on the client
SASVI_VERIFY_SSLTLS verification: true (check against the operating system's trust store), false, or the path of a CA bundle file or certificate directorytrue on both

Case 3 passes through whichever of SASVI_CLIENT_ID and SASVI_CLIENT_SECRET is set, and falls back to the sas.cli client id when SASVI_CLIENT_ID is not. Only one of the pair can ever reach case 3, because setting both matches case 2 first.

An explicit constructor keyword takes precedence over the environment variable for the same setting, provided you pass a real value rather than an empty one.

See the Client reference for the exact constructor behavior.

from_env() versus the CLI​

The sasvi command line and SVIClient.from_env() share one resolver, sasvi.settings.resolve_settings(). The difference is what each asks it to read:

Source (highest first)SVIClient.from_env()sasvi CLI
Explicit keywords / optionsYesYes
Process environmentYesYes
A .env fileWith env_file=--env-file, else ./.env when present
A profile from profiles.tomlWith profile=--profile, else SASVI_PROFILE, else the default
sasvi auth login token cacheWith use_login_cache=TrueAlways

Each layer only fills settings the layers above left unset. The login cache supplies SASVI_ACCESS_TOKEN only when no layer above sets one and the base URL in use is the host the login was made for. When it does, it outranks SASVI_CLIENT_ID/SASVI_CLIENT_SECRET and SASVI_USERNAME/SASVI_PASSWORD, because an access token is checked first. Nothing is written to os.environ.

To get the CLI's behavior in Python:

from sasvi import SVIClient
from sasvi.profiles import active_profile_name

svi = SVIClient.from_env(env_file=".env", profile=active_profile_name(), use_login_cache=True)
print(svi.environment_host) # check the tenant before you write

resolve_settings() takes the same arguments and returns every effective setting with its source (override, environment, env-file, profile or login-cache), without building a client.

sasvi auth status shows what the CLI would use, and every CLI command prints the tenant and credential source on stderr. See Which tenant is this using?.

Original SAS API docs​

Next references​