Using SDK to call your application server
How to make authorized request to your application server after login with Authgear

Using Authgear SDK to call your application server

In this section, we are going to explain how to make an authorized request to your application server by using Authgear SDK. If you are using Cookie-based authentication in your web application, you can skip this section as session cookies are handled by the browser automatically.

Setup Overview

    1.
    To determine which user is calling your server, you will need to include the Authorization header in every request that send to your application server.
    2.
    You will need to set up Backend integration, Authgear will help you to resolve the Authorization header to determine whether the incoming HTTP request is authenticated or not.
In the below section, we will explain how to set up SDK to include Authorization header to your application requests.

SDK setup

Configuration

Configure the Authgear SDK with the Authgear endpoint and client id. The SDK must be properly configured before use, you can call configure multiple times but you should only need to call it once. No network call will be triggered during configure.
Javascript
iOS
Android
1
authgear
2
.configure({
3
clientID: "<YOUR_APPLICATION_CLIENT_ID>",
4
endpoint: "<YOUR_AUTHGEAR_ENDPOINT>",
5
})
6
.then(() => {
7
// configured successfully
8
})
9
.catch((e) => {
10
// failed to configured
11
});
Copied!
1
let authgear = Authgear(clientId: clientId, endpoint: endpoint)
2
authgear.configure() { result in
3
switch result {
4
case .success():
5
// configured successfully
6
case let .failure(error):
7
// failed to configured
8
}
9
}
Copied!
1
ConfigureOptions configureOptions = new ConfigureOptions();
2
Authgear authgear = new Authgear(getApplication(), clientID, endpoint, null);
3
authgear.configure(configureOptions, new OnConfigureListener() {
4
@Override
5
public void onConfigured() {
6
// configured successfully
7
}
8
9
@Override
10
public void onConfigurationFailed(@NonNull Throwable throwable) {
11
// failed to configured
12
}
13
});
Copied!

Get the latest session state

sessionState reflect the user logged in state. Right after configure, the session state only reflects the SDK local state. That means even sessionState is AUTHENTICATED, the session may be invalid if it is revoked remotely. You will only know that after calling the server, call fetchUserInfo as soon as it is proper to do so, e.g. when the device goes online.
Javascript
iOS
Android
1
// value can be NO_SESSION or AUTHENTICATED
2
// After authgear.configure, it only reflect SDK local state.
3
let sessionState = authgear.sessionState;
4
5
if (sessionState === "AUTHENTICATED") {
6
authgear
7
.fetchUserInfo()
8
.then((userInfo) => {
9
// sessionState is now up to date
10
// read the userInfo if needed
11
})
12
.catch((e) => {
13
// sessionState is now up to date
14
// it will change to NO_SESSION if the session is invalid
15
});
16
}
Copied!
1
// value can be .noSession or .authenticated.
2
// After authgear.configure, it only reflect SDK local state.
3
let sessionState = authgear.sessionState
4
5
// call fetchUserInfo to see if the session is valid
6
if authgear.sessionState == .authenticated {
7
authgear.fetchUserInfo { userInfoResult in
8
// sessionState is now up to date
9
// it will change to .noSession if the session is invalid
10
let sessionState = authgear.sessionState
11
12
switch userInfoResult {
13
case let .success(userInfo):
14
// read the userInfo if needed
15
case let .failure(error):
16
// failed to fetch user info
17
// the refresh token maybe expired or revoked
18
}
19
}
Copied!
1
// value can be NO_SESSION or AUTHENTICATED
2
// After authgear.configure, it only reflect SDK local state.
3
SessionState sessionState = authgear.getSessionState();
4
5
if (sessionState == SessionState.AUTHENTICATED) {
6
authgear.fetchUserInfo(new OnFetchUserInfoListener() {
7
@Override
8
public void onFetchedUserInfo(@NonNull UserInfo userInfo) {
9
// sessionState is now up to date
10
// read the userInfo if needed
11
}
12
13
@Override
14
public void onFetchingUserInfoFailed(@NonNull Throwable throwable) {
15
// sessionState is now up to date
16
// it will change to NO_SESSION if the session is invalid
17
}
18
});
19
}
Copied!

Calling an API

Use fetch function from the SDK (JavaScript Only)

Javascript Only. Authgear SDK provides fetch function for you to call your application server. The fetch function will include Authorization header in your application request, and handle refresh access token automatically. authgear.fetch implement fetch. If you are using another networking library and want to include the Authorization header yourself. You can skip this and go to the next step.
Javascript
1
authgear
2
.fetch("YOUR_SERVER_URL")
3
.then(response => response.json())
4
.then(data => console.log(data));
Copied!

Add the access token to the HTTP request header

You will need to include the Authorization header in your application request. Call refreshAccessTokenIfNeeded every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of your application request.
Javascript
iOS
Android
1
authgear
2
.refreshAccessTokenIfNeeded()
3
.then(() => {
4
// access token is ready to use
5
// accessToken can be string or undefined
6
// it will be empty if user is not logged in or session is invalid
7
const accessToken = authgear.accessToken;
8
9
// include Authorization header in your application request
10
const headers = {
11
Authorization: `Bearer ${accessToken}`
12
};
13
});
Copied!
1
authgear.refreshAccessTokenIfNeeded() { result in
2
switch result {
3
case .success():
4
// access token is ready to use
5
// accessToken can be empty
6
// it will be empty if user is not logged in or session is invalid
7
8
// include Authorization header in your application request
9
if let accessToken = authgear.accessToken {
10
// example only, you can use your own networking library
11
var urlRequest = URLRequest(url: "YOUR_SERVER_URL")
12
urlRequest.setValue(
13
"Bearer \(accessToken)", forHTTPHeaderField: "authorization")
14
// ... continue making your request
15
}
16
case let .failure(error):
17
// failed to refresh access token
18
// the refresh token maybe expired or revoked
19
}
20
}
Copied!
1
// Suppose we are preparing an http request in a background thread.
2
3
// Setting up the request, e.g. preparing a URLConnection
4
5
try {
6
authgear.refreshAccessTokenIfNeededSync();
7
} catch (OauthException e) {
8
// The token is expired.
9
}
10
String accessToken = authgear.getAccessToken();
11
if (accessToken == null) {
12
// The user is not logged in, or the token is expired.
13
// It is up to the caller to decide how to handle this situation. Typically, the request could be aborted
14
// immediately as the response would be 401 anyways.
15
return;
16
}
17
18
HashMap<String, String> headers = new HashMap<>();
19
headers.put("authorization", "Bearer " + accessToken);
20
21
// Submit the request with the headers...
Copied!

Handle revoked sessions

If the session is revoked from the management portal, the client will call your application server with an invalid access token. Your application server can check that by looking at the resolver headers.
For example, you application may return HTTP status code 401 for unauthorized requests. Depending on your application flow, you may want to show your user login page again or reset the SDK sessionState to NO_SESSION locally. To clear the sessionState, you can use clearSessionState function.
Javascript
iOS
Android
1
// example only
2
// if your application server return HTTP status code 401 for unauthorized request
3
async function fetchAppServer() {
4
var response = await authgear.fetch("YOUR_SERVER_URL");
5
if (response.status === 401) {
6
7
// if you want to clear the session state locally, call clearSessionState
8
// `authgear.sessionState` will become `NO_SESSION` after calling
9
await authgear.clearSessionState();
10
throw new Error("user session invalid");
11
}
12
// ...
13
}
Copied!
1
// example only
2
// if your application server return HTTP status code 401 for unauthorized request
3
if let response = response as? HTTPURLResponse {
4
if response.statusCode == 401 {
5
6
// if you want to clear the session state locally, call clearSessionState
7
// `authgear.sessionState` will become `.noSession` after calling
8
authgear.clearSessionState { result in
9
switch result {
10
case .success():
11
// clear SDK session state locally
12
// `authgear.sessionState` becomes `.noSession`
13
case let .failure(error):
14
// failed to clear session state
15
}
16
}
17
}
18
}
Copied!
1
// example only
2
// if your application server return HTTP status code 401 for unauthorized request
3
responseCode = httpConn.getResponseCode();
4
if (responseCode != HttpURLConnection.Unauthorized) {
5
6
// if you want to clear the session state locally, call clearSessionState
7
// ` authgear.getSessionState()` will become `NO_SESSION` after calling
8
authgear.clearSessionState();
9
}
Copied!
Last modified 4mo ago