AI translation
This page was translated from German with AI. If in doubt, the German original applies.
Sessions and tokens¶
The auth model — three-tier, with rotation of the refresh token on every access request, and directly with an API key for processes without a user — is described under Getting started → The auth model and applies equally to REST, gRPC, and the SDK. This section only covers what is specific to the SDK.
The logins¶
// 1) Separate fields
await client.CreateSession(
providerId: 1,
subscriberId: "mysubscriber",
accountId: "myaccount",
password: "mypassword",
appToken: new AppToken(appTokenJwt));
// 2) Combined UserId
await client.CreateSession(
userId: "mysubscriber-myaccount@1:mypassword",
appToken: new AppToken(appTokenJwt));
AppToken, AccessToken, and RefreshToken live in Zedal.Sdk.Jwt. They are wrappers around a JWT; the constructor takes the encoded string.
The UserId variant does not allow separators within its components
The pattern is <subscriber>-<account>@<provider>:<password>; the SDK splits it at -, @, and :. If a component — especially the password — contains one of these characters, the call fails with RpcException (InvalidArgument, “Input does not match the expected pattern”) before any network call is made. For anything automated, use variant 1.
With variant 1, you specify the providerId yourself. Variant 2 derives it from the provider part of the UserId. ContinueSession reads it from the refresh token. If the resolved provider ID is 0, the call aborts with RpcException (InvalidArgument, “active provider not set”).
Token rotation and the callback¶
SetAccessTokenChanged registers a callback that receives the current pair (AccessToken accessToken, RefreshToken refreshToken) on every rotation. It is the only way to learn the currently valid refresh token.
client.SetAccessTokenChanged(tokens =>
SecureStorage.Save("zedal-refresh-token", tokens.refreshToken.Jwt.EncodedToken));
The encoded JWT string is in Jwt.EncodedToken; ToByteArray() returns the same string as UTF-8 bytes. If you want to store the token in binary form, IRefreshTokenStore (SaveTokenAsync(byte[]), LoadTokenAsync(), DeleteTokenAsync()) is a suitable interface to implement yourself.
Register the callback before login and before ContinueSession, otherwise it misses the first rotation.
Token renewal¶
There is no lifetime stored in the client, and you shouldn’t assume one either. Both tokens are JWTs and carry their expiration time in the exp claim; in the SDK, you read it via token.Jwt.ValidTo.
| Question | Answer |
|---|---|
| When does the SDK renew on its own? | As soon as the remaining lifetime of the access token drops below 5 minutes — checked before every call that needs a token. |
| Who does that? | DefaultTokenRefresher, the standard implementation of IJwtTokenRefresh. A semaphore ensures that only one renewal runs at a time within a client. |
What does AccessToken.IsValid(scopeInMinutes) return? |
true if the token is still valid in scopeInMinutes. The default is 2 minutes; the refresher asks with 5. |
| Can I replace this? | Yes — pass your own IJwtTokenRefresh implementation to CreateClient(..., tokenRefresh: …). The default implementation checks only the expiration date; it does not handle revoked or locked access. |
A failed refresh ends as Unauthenticated
If the renewal fails, DefaultTokenRefresher returns an empty token. The actual call then ends with RpcException (Unauthenticated); the cause (network error, rotated token, revoked session) is not included. If you need to distinguish these cases, implement IJwtTokenRefresh yourself.
For parallel processes, the rule remains unchanged: a refresh token belongs to exactly one process. Two clients with the same stored token invalidate each other — see Token rotation.
Sessions with an API key¶
For processes without a user — integrations, ERP connections, scripts — an API key replaces the login with a password. The SDK exchanges it together with the app token directly for an access token; no refresh token is created. So there is nothing to rotate and nothing to store after a refresh: the process holds only the key. A runnable sample is api-key.
Creating a key¶
You create API keys in the ZEDAL portal under “Mein ZEDAL” → “API-Keys”, for the account logged in there; the SDK does not create any. To create one, the portal asks for the account’s password again, because the key remains valid beyond the session. When creating a key, you choose the scopes it may grant — core, dataexport, wastemanager, nothing is implied — and optionally an expiration date. The portal shows the key only right after creating it; store it as securely as a password.
The key belongs to the account it was created for and acts with that account’s permissions. Every account creates keys only for itself, the main account included; in the portal, the main account also sees the keys of its users and can revoke them. If the key should not depend on a person’s login, create it for a separate account for the integration.
Logging in with the key¶
await client.CreateSession(
apiKey: new ApiKey(SecureStorage.Load("zedal-api-key")),
appToken: new AppToken(appTokenJwt));
var missing = client.CoreApi.Auth.NotGrantedScopes;
if (missing.Count > 0)
{
Console.WriteLine("API key does not grant: " + string.Join(", ", missing));
}
ApiKey lives in Zedal.Sdk.Jwt but is no JWT: the constructor takes the key as the portal issues it (zedal_ak_…) and throws ArgumentException if the value is none — without repeating it in the message. ToString() shows the key without its secret.
The access token carries only the scopes that both the key and the app token have; you read them with client.CoreApi.Auth.AccessToken.GetScope(). NotGrantedScopes lists the scopes of the app token that a key could grant but this key does not. Whether your application needs them depends on the calls it makes.
| Question | Answer |
|---|---|
| How is the token renewed? | As in every session, as soon as the remaining lifetime of the access token drops below 5 minutes. Instead of a refresh token, the SDK exchanges the key again. |
| What does the callback receive? | AccessTokenChanged fires on every exchange, with refreshToken == null. |
| May several processes use the same key? | Yes, a key does not rotate. Every exchange counts against the key’s limit, though (see below). |
| What happens with an invalid key? | An unknown, revoked, or expired key results in RpcException with Unauthenticated, as does a locked account. |
Don’t exchange the key before every call
The server limits how often a key can be exchanged within a period of time; beyond that, it responds with RpcException, status ResourceExhausted. The SDK keeps using the access token until shortly before it expires. If you create a new client and call CreateSession for every call, you run into the limit. Keep one client per process and let it renew on its own — or keep the access token between runs (next section).
Keeping the access token between program runs¶
If your application starts anew for every run — a command-line tool, a cron job —, every run costs an exchange. In that case, keep the access token and continue the session with it:
client.SetAccessTokenChanged(tokens =>
SecureStorage.Save("zedal-access-token", tokens.accessToken.Jwt.EncodedToken));
var kept = SecureStorage.Load("zedal-access-token");
await client.ContinueSession(
apiKey: new ApiKey(SecureStorage.Load("zedal-api-key")),
appToken: new AppToken(appTokenJwt),
accessToken: kept == null ? null : new AccessToken(kept));
ContinueSession uses the token you pass without an exchange as long as it was issued for this key and this app token and has not expired. Otherwise, it exchanges the key like CreateSession and reports the new token via the callback. Without an exchange, NotGrantedScopes stays empty. Store the access token as securely as the key: until its exp, it allows everything the key allows.
Revoking a key¶
Revoking happens in the portal, in the same place. After that, the key no longer yields a new access token; access tokens already issued may remain valid until they expire. In a session with an API key, EndSession only forgets the key and the access token; the key itself stays valid until you revoke it in the portal.
Ending a session¶
EndSession tries to revoke the refresh token on the server and then clears the local state in any case (AccessToken, RefreshToken, ActiveProvider).
EndSession does not report failure
If the server-side revocation fails, for example without a network connection or when the deadline is exceeded, EndSession still returns normally: the session has ended locally, but possibly not on the server. If you need to be sure that a token is no longer valid, use the auth operations directly: client.CoreApi.Auth.RevokeRefreshTokenByToken(...) or RevokeRefreshTokenByFamilyId(...), and handle the exception.
Ending all sessions¶
Changing the password does not end running sessions by itself. If a refresh token may have fallen into the wrong hands, end all sessions of the account deliberately: ListSessions lists them with their family id, RevokeRefreshTokenByFamilyId ends each one. Your own session ends as well; log in again afterwards.
foreach (var entry in await client.CoreApi.Auth.ListSessions())
{
if (entry.JwtSession is { } session)
await client.CoreApi.Auth.RevokeRefreshTokenByFamilyId(session.FamilyId);
}
await client.EndSession(); // clears the local state; the own session is revoked as well
Session management via CoreApi.Auth¶
Whatever the facade doesn’t cover is on client.CoreApi.Auth:
| Method | Purpose |
|---|---|
ListSessions() |
Lists the active sessions of the account. |
RevokeRefreshTokenByToken(token) / RevokeRefreshTokenByFamilyId(familyId) |
Revokes a single token or an entire token family. |
RefreshAccessToken() |
Renews immediately, without waiting for the 5-minute threshold. |
EnsureLoggedIn() |
Throws RpcException (Unauthenticated) if no refresh token is present; fetches a missing access token. |
AccessToken, RefreshToken, ActiveProvider |
The current session state as properties. |