The SDK keeps track of the authenticated token and auth model for you via the xg.authStore
instance.
LocalCookieAuthStore (default)
The default LocalCookieAuthStore uses the browser's document.cookie
storage if available, otherwise - will fallback to runtime/memory (aka. on page refresh or service restart you'll have to authenticate again).
Default cookie names
xgen_token
- token value and expiration datexgen_user
- user value and expiration datexgen_session
- session value and expiration date
Custom auth store
In some situations it could be easier to create your own custom auth store. For this you can extend BaseAuthStore
and pass the new custom instance as constructor argument to the client:
import XGenClient, { BaseAuthStore } from '@xgenai/sdk-core';
class CustomAuthStore extends BaseAuthStore {
save({tokenRecord, userRecord, sessionRecord}) {
super.save({tokenRecord, userRecord, sessionRecord});
// your custom business logic...
}
}
const xg = new XGenClient({
// ...other params
authStore: new CustomAuthStore()
});
Common auth store fields and methods
The default xg.authStore
extends BaseAuthStore
and has the following public members that you can use:
BaseAuthStore {
// base fields
token: TokenRecord|null // the access_token and expiration
user: UserRecord|null // the userId, userType, and expiration
sessionId: SessionRecord|null // the session id and expiration
isExpired: boolean // checks if the record is expired
// main methods
clear() // "logout" the authenticated record
save({tokenRecord, userRecord, sessionRecord}) // update the store with the new auth data
// cookie parse and serialize helpers
loadFromCookie(cookieHeader)
exportToCookie(options = {})
}
To "logout" the authenticated record you can call xg.authStore.clear()
.
To manually cancel pending requests, you could use xg.cancelAll()
or xg.cancel(requestKey)
.
Custom Cookie names
import XGenClient, {LocalCookieAuthStore} from '@xgenai/sdk-core';
const authStore = new LocalCookieAuthStore({
keyPrefix = 'custom_',
tokenSuffix = 'my-token-key',
userSuffix = 'my-user-key',
sessionSuffix = 'my-session-key',
})
Now the cookie keys stored in the browser will be.
custom_my-token-key
- Stores authentication token and expiration datecustom_my-user-key
- Contains user information and expiration datecustom_my-session-key
- Maintains session data and expiration date