The browser opens Geens login in a popup. On the registered redirect page,
initialize the SDK with the same configuration after the page body exists.
The constructor processes Geens' code and private query parameters and
passes the code to the application window. Do not call finalizeLogin on that
redirect page; the original application window completes the login.
Register the callback once on your application's SDK instance, then open the popup from a user gesture, such as a button click:
sdk.onLogin(async code => {
try {
const response = await fetch('/oauth/exchange', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
});
if (!response.ok) {
throw new Error(`Token exchange failed: ${response.status}`);
}
const token = await response.json();
sdk.finalizeLogin(token, undefined, true, () => {
console.log('Login completed');
}, onError);
} catch (error) {
onError(error);
}
});
document.getElementById('geens-login').addEventListener('click', () => {
sdk.openLogin();
});
Add a button with id="geens-login" to your page. /oauth/exchange is an endpoint
you implement in your application backend. It exchanges the code with Geens and
returns this token object, not just the access-token string:
{
"access_token": "access-token-from-geens",
"expires_in": 3600,
"token_type": "Bearer"
}
finalizeLogin(token, redirectUrl, reloadWindow, onSuccess, onError) stores the
token and loads the user's data. redirectUrl is optional; reloadWindow
defaults to true. The default page reload restores the SDK's session state.
Passing false suppresses that reload. sdk.loggedIn reflects locally restored
session state; it does not verify that the server still accepts the token.
Send a form-encoded POST to /api/oauth/access_token on the same Geens server
configured in the SDK. Include grant_type=authorization_code, code,
client_id, client_secret, and redirect_uri.
Keep the client secret and refresh token on your backend. Associate the refresh
token with the user's application session and return only access_token,
expires_in, and token_type to the browser. Your application's exchange and
refresh endpoints must validate the user's session and protect requests against
CSRF according to your framework's conventions.
For example, this Node.js helper uses built-in fetch. Call it from your
/oauth/exchange handler with the submitted code and the user's backend session,
and return the result as JSON:
async function exchangeAuthorizationCode(code, session) {
const response = await fetch('https://geens.com/api/oauth/access_token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: process.env.GEENS_CLIENT_ID,
client_secret: process.env.GEENS_CLIENT_SECRET,
redirect_uri: process.env.GEENS_REDIRECT_URI
})
});
if (!response.ok) {
throw new Error(`Token exchange failed: ${response.status}`);
}
const token = await response.json();
if (!token.access_token) {
throw new Error('Token exchange did not return an access token');
}
session.geensRefreshToken = token.refresh_token;
// Persist the session using your framework's session store.
return {
access_token: token.access_token,
expires_in: token.expires_in,
token_type: token.token_type
};
}
Set GEENS_CLIENT_ID, GEENS_CLIENT_SECRET, and GEENS_REDIRECT_URI in your
backend environment. Session storage and HTTP routing belong to your application.
The same exchange in other backend environments:
<?php
// Obtain $authorizationCode from the validated application request.
$curl = curl_init('https://geens.com/api/oauth/access_token');
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'authorization_code',
'code' => $authorizationCode,
'client_id' => getenv('GEENS_CLIENT_ID'),
'client_secret' => getenv('GEENS_CLIENT_SECRET'),
'redirect_uri' => getenv('GEENS_REDIRECT_URI'),
]),
]);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($response === false || $status < 200 || $status >= 300) {
throw new RuntimeException('Token exchange failed: ' . ($error ?: $status));
}
$token = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
if (empty($token['access_token'])) {
throw new RuntimeException('Token exchange did not return an access token');
}
// Persist $token['refresh_token'] in the user's backend session.
header('Content-Type: application/json');
echo json_encode([
'access_token' => $token['access_token'],
'expires_in' => $token['expires_in'],
'token_type' => $token['token_type'],
]);
?>
import http.client
import json
import os
import urllib.parse
# Obtain authorization_code from the validated application request.
conn = http.client.HTTPSConnection('geens.com', 443)
payload = urllib.parse.urlencode({
'grant_type': 'authorization_code',
'code': authorization_code,
'client_id': os.environ['GEENS_CLIENT_ID'],
'client_secret': os.environ['GEENS_CLIENT_SECRET'],
'redirect_uri': os.environ['GEENS_REDIRECT_URI'],
})
conn.request('POST', '/api/oauth/access_token', payload, {
'Content-Type': 'application/x-www-form-urlencoded',
})
response = conn.getresponse()
body = response.read()
conn.close()
if not 200 <= response.status < 300:
raise RuntimeError(f'Token exchange failed: {response.status}')
token = json.loads(body)
if not token.get('access_token'):
raise RuntimeError('Token exchange did not return an access token')
# Persist token['refresh_token'] in the user's backend session.
frontend_response = {key: token[key] for key in (
'access_token', 'expires_in', 'token_type'
)}
# Return frontend_response as JSON from your application's exchange endpoint.
curl --fail-with-body -X POST \
https://geens.com/api/oauth/access_token \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode "code=$GEENS_AUTHORIZATION_CODE" \
--data-urlencode "client_id=$GEENS_CLIENT_ID" \
--data-urlencode "client_secret=$GEENS_CLIENT_SECRET" \
--data-urlencode "redirect_uri=$GEENS_REDIRECT_URI"
Set these variables in your backend environment. This command returns the raw OAuth response; store its refresh token and filter it before responding to the browser. Do not run this request from browser code.
To refresh an access token, call your application's backend. The backend must
send a POST request to /api/oauth/refresh-oauth-token with
grant_type=refresh_token, client_id, client_secret, and refresh_token.
As with exchanging the authorization code, this request requires the OAuth
client secret and must run on the backend.
Store the refresh token returned by the initial authorization-code exchange
on your backend, associated with the user's session. Use that stored token for
refresh requests. If the refresh response includes a new refresh_token, replace
the stored token with it. Return only access_token, expires_in, and token_type
to the frontend; keep the refresh token and client secret on the backend.
Example of backend in Node.js (using the built-in fetch). Replace
yourStoredRefreshToken with the refresh token loaded from the user's backend
session, and configure the client credentials in the backend environment.
const response = await fetch('https://geens.com/api/oauth/refresh-oauth-token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: process.env.GEENS_CLIENT_ID,
client_secret: process.env.GEENS_CLIENT_SECRET,
refresh_token: 'yourStoredRefreshToken',
}),
});
if (!response.ok) {
throw new Error(`Token refresh failed: ${response.status}`);
}
const token = await response.json();
if (!token.access_token) {
throw new Error('Token refresh did not return an access token');
}
// Save token.refresh_token, if returned, to the user's backend session.
const frontendResponse = {
access_token: token.access_token,
expires_in: token.expires_in,
token_type: token.token_type,
};
// Return frontendResponse as JSON from your application's refresh endpoint.
Example of backend in PHP.
<?php
$curl = curl_init('https://geens.com/api/oauth/refresh-oauth-token');
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'refresh_token',
'client_id' => getenv('GEENS_CLIENT_ID'),
'client_secret' => getenv('GEENS_CLIENT_SECRET'),
'refresh_token' => 'yourStoredRefreshToken',
]),
]);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($response === false || $status < 200 || $status >= 300) {
throw new RuntimeException('Token refresh failed: ' . ($error ?: $status));
}
$token = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
if (empty($token['access_token'])) {
throw new RuntimeException('Token refresh did not return an access token');
}
// Save $token['refresh_token'], if returned, to the user's backend session.
header('Content-Type: application/json');
echo json_encode([
'access_token' => $token['access_token'],
'expires_in' => $token['expires_in'],
'token_type' => $token['token_type'],
]);
?>
Example of backend in Python.
import http.client
import json
import os
import urllib.parse
conn = http.client.HTTPSConnection('geens.com', 443)
payload = urllib.parse.urlencode({
'grant_type': 'refresh_token',
'client_id': os.environ['GEENS_CLIENT_ID'],
'client_secret': os.environ['GEENS_CLIENT_SECRET'],
'refresh_token': 'yourStoredRefreshToken',
})
conn.request('POST', '/api/oauth/refresh-oauth-token', payload, {
'Content-Type': 'application/x-www-form-urlencoded',
})
response = conn.getresponse()
body = response.read()
conn.close()
if not 200 <= response.status < 300:
raise RuntimeError(f'Token refresh failed: {response.status}')
token = json.loads(body)
if not token.get('access_token'):
raise RuntimeError('Token refresh did not return an access token')
# Save token['refresh_token'], if returned, to the user's backend session.
frontend_response = {key: token[key] for key in (
'access_token', 'expires_in', 'token_type'
)}
# Return frontend_response as JSON from your application's refresh endpoint.
Example of a refresh request in cURL, run on the backend. Set
GEENS_CLIENT_ID, GEENS_CLIENT_SECRET, and GEENS_REFRESH_TOKEN in the backend
environment. This request returns the OAuth response, including any new refresh
token; your backend must store that token and filter the response before sending
it to the frontend.
curl --fail-with-body -X POST \
https://geens.com/api/oauth/refresh-oauth-token \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode "client_id=$GEENS_CLIENT_ID" \
--data-urlencode "client_secret=$GEENS_CLIENT_SECRET" \
--data-urlencode "refresh_token=$GEENS_REFRESH_TOKEN"
When your application's refresh endpoint returns the access token data, pass
it to setAccessToken to update the SDK's access token and expiration date:
async function refreshAccessToken() {
const response = await fetch('/refresh-token', {
method: 'POST',
credentials: 'same-origin'
});
if (!response.ok) {
throw new Error(`Token refresh failed: ${response.status}`);
}
const token = await response.json();
sdk.setAccessToken({
access_token: token.access_token,
expires_in: token.expires_in,
token_type: token.token_type
});
}
The /refresh-token route above belongs to your application. The SDK does not
request refreshes or store refresh tokens. You can use
getNotificationBeforeAccessTokenExpires to trigger your application's backend
refresh flow before the current access token expires. If the backend cannot
refresh the token, start the login flow again.
After the SDK restores a logged-in session, register a callback with
getNotificationBeforeAccessTokenExpires(minutesBeforeExpiration, callback).
The default threshold is one minute; values must be at least 1. The callback
receives the remaining seconds, or 0 when already expired. The SDK polls about
every 20 seconds, so the notification is approximate. It does not detect an
early server-side token revocation.
Using the refreshAccessToken helper above:
function scheduleTokenRefresh() {
sdk.getNotificationBeforeAccessTokenExpires(1, async () => {
try {
await refreshAccessToken();
scheduleTokenRefresh(); // Register again for the new token's expiration.
} catch (error) {
onError(error);
// Ask the user to log in again using the login button.
}
});
}
if (sdk.loggedIn) {
scheduleTokenRefresh();
}
Call sdk.openLogout() from a user gesture. When logoutUri is configured,
Geens logout opens in a popup. On that application's logout callback page,
initialize the SDK and finish logout:
sdk.finalizeLogout();
This clears local storage, reloads the original application window, and closes
the popup. finalizeLogout(redirectUrl, reloadWindow) also accepts an optional
redirect and a reload flag that defaults to true. Call it only from the logout
popup page, where window.opener exists.
Without logoutUri, openLogout() clears the local session and reloads the
application directly; it does not open the Geens logout popup. To clear only
local session data without navigating:
sdk.clearLocalStorage(null, false);
clearLocalStorage(redirectUrl, reloadWindow) can redirect or reload the current
page; reload defaults to true. These cleanup methods call localStorage.clear()
and remove all local-storage entries for the application's origin, including
entries your application stored independently.