Use SDK to make authorized API calls to backend

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 backend API by using Authgear SDK. Authgear SDKs make it easy to refresh access token if needed and maintain session state.

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.

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. On your Backend/API, you will need to set up Backend integration. Authgear will help you to handle 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 for the purpose of making authorized API calls to your backend.

SDK Setup

Configure the Authgear SDK with the Authgear endpoint and client id. The SDK must be properly configured before use by calling configure. No network call will be triggered during configure.

authgear
    .configure({
        clientID: "<YOUR_APPLICATION_CLIENT_ID>",
        endpoint: "<YOUR_AUTHGEAR_ENDPOINT>",
    })
    .then(() => {
        // configured successfully
    })
    .catch((e) => {
        // failed to configured
    });

UserInfo and Session State

sessionState reflect the user logged in state. However the session state is cached locally and only updated after each server call.

Usually right after login/signup via authorize,You will call fetchUserInfo as soon as possible with authgear.sessionState became AUTHENTICATED

// value can be NO_SESSION or AUTHENTICATED
// After authgear.configure, it only reflect SDK local state.
let sessionState = authgear.sessionState;

if (sessionState === "AUTHENTICATED") {
    authgear
        .fetchUserInfo()
        .then((userInfo) => {
            // sessionState is now up to date
            // read the userInfo if needed
        })
        .catch((e) => {
            // sessionState is now up to date
            // it will change to NO_SESSION if the session is invalid
        });
}

Makeing an API call

When you make a API call to Backend API, you will need to include the access token in the Authorization header. Access token is also short lived and need to be regularly rotated by Refresh token for security purpose. Authgear SDKs provide the following functions to simplify both steps.

The fetch function (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, you will need to use refreshAccessTokenIfNeeded(). and include the Authorization header yourself, as described in the next paragraph.

authgear
    .fetch("YOUR_SERVER_URL")
    .then(response => response.json())
    .then(data => console.log(data));

The refreshAccessTokenIfNeeded function

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.

authgear
    .refreshAccessTokenIfNeeded()
    .then(() => {
        // access token is ready to use
        // accessToken can be string or undefined
        // it will be empty if user is not logged in or session is invalid
        const accessToken = authgear.accessToken;

        // include Authorization header in your application request
        const headers = {
            Authorization: `Bearer ${accessToken}`
        };
    });

Handle revoked sessions

If the session is revoked from the management portal, the client will call your Backend API 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.

// example only
// if your application server return HTTP status code 401 for unauthorized request
async function fetchAppServer() {
    var response = await authgear.fetch("YOUR_SERVER_URL");
    if (response.status === 401) {

        // if you want to clear the session state locally, call clearSessionState
        // `authgear.sessionState` will become `NO_SESSION` after calling
        await authgear.clearSessionState();
        throw new Error("user session invalid");
    }
    // ...
}

Last updated

#293: create getting started overview page

Change request updated