Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • 5-Minute Guide
    • Start Building
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Client SDK to make authorized API calls to backend
      • Validate JWT in your backend
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
    • Integration by OIDC
    • Integration by SAML
      • Use Authgear as SAML Identity Provider for Salesforce
      • Use Authgear as SAML Identity Provider for Dropbox
      • SAML Attribute Mapping
  • Authentication and Access
    • Authentication
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Enable Two-Factor Authentication (2FA)
      • Re-authentication
      • Set Password Expiry
      • Change Forgot/Reset Password settings
      • Add authentication to any web page
    • Single Sign-on Overview
      • App2App Login
      • App2Web (Pre-authenticated URLs)
      • Web2App (From Mobile Apps to Browsers)
      • Force Authgear to Show Login Page
      • Single Sign-on with OIDC
      • Single Sign-on with SAML
    • Social/Enterprise Login Providers Overview
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
  • FAQ for Authentication
    • Tips for Apple App Store Review with Passwordless Login
    • Phone Number Validation
    • Skip Login Screen and Direct Users to Enterprise Login
    • Use the OAuth 2.0 State Parameter
    • Local Dev Setup for Connecting to Authgear SaaS in Cookie-based Auth
  • Integration
    • Add custom fields to a JWT Access Token
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Mobile Apps
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Integration with other Software
      • Integrate Authgear with Firebase
      • Integrate with Google Tag Manager
    • FAQ for Integration
      • How to Track User Before and After Signup?
      • What happens with user directly access the Authgear Endpoint?
  • Customization
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
      • Languages and Localization
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Custom Domain
    • Custom Email and SMS Templates
    • Custom Email Provider
    • Custom SMS Provider
      • Twilio
      • Webhook/Custom Script
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Example: Only Allow Signups from Inside the Corporate Network using Hooks
  • Admin & Operations
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • API Queries and Mutations
        • Using global node IDs
        • Retrieving users using Admin API
        • API Examples
          • Generate OTP code
          • Search for users
          • Update user's picture
          • Update user's standard attributes
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • Supported Scopes
        • UserInfo
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Rate Limits
      • Account Lockout
    • Glossary
    • Billing FAQ
  • Authgear ONCE
    • What is Authgear ONCE
    • Install Authgear ONCE on a VM
    • Install Authgear ONCE on Amazon Web Services (AWS)
    • Install Authgear ONCE on Vultr
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deployment
    • Run with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configuration
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Architecture Guides
      • AWS Reference Architecture
      • Azure Reference Architecture
      • Google Cloud Reference Architecture
      • Throughput Scaling Reference
  • Troubleshooting
    • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
    • How to Fix CORS Error
Powered by GitBook
On this page
  • Using Authgear SDK to call your application server
  • Overview
  • SDK Setup
  • UserInfo and Session State
  • Makeing an API call
  • The fetch function (JavaScript Only)
  • The refreshAccessTokenIfNeeded function
  • Handle revoked sessions

Was this helpful?

Edit on GitHub
Export as PDF
  1. Get Started
  2. Backend/API Integration

Client SDK to make authorized API calls to backend

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

PreviousBackend/API IntegrationNextValidate JWT in your backend

Last updated 5 days ago

Was this helpful?

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 . 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
    });
let authgear = Authgear(clientId: clientId, endpoint: endpoint)
authgear.configure() { result in
    switch result {
    case .success():
        // configured successfully
    case let .failure(error):
        // failed to configured
    }
}
ConfigureOptions configureOptions = new ConfigureOptions();
Authgear authgear = new Authgear(getApplication(), clientID, endpoint);
authgear.configure(configureOptions, new OnConfigureListener() {
    @Override
    public void onConfigured() {
        // configured successfully
    }

    @Override
    public void onConfigurationFailed(@NonNull Throwable throwable) {
        // failed to configured
    }
});
var authgearOptions = new AuthgearOptions
{
    ClientId = "<YOUR_APPLICATION_CLIENT_ID>",
    AuthgearEndpoint: "<YOUR_AUTHGEAR_ENDPOINT>",
};
#if __ANDROID__
var authgear = new AuthgearSdk(GetActivity().ApplicationContext, authgearOptions);
#else
#if __IOS__
var authgear = new AuthgearSdk(UIKit.UIApplication.SharedApplication, authgearOptions);
#endif
#endif
await authgear.ConfigureAsync();

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
        });
}
// value can be .noSession or .authenticated.
// After authgear.configure, it only reflect SDK local state.
let sessionState = authgear.sessionState

// call fetchUserInfo to see if the session is valid
if authgear.sessionState == .authenticated {
    authgear.fetchUserInfo { userInfoResult in
        // sessionState is now up to date
        // it will change to .noSession if the session is invalid
        let sessionState = authgear.sessionState

        switch userInfoResult {
        case let .success(userInfo):
            // read the userInfo if needed
        case let .failure(error):
            // failed to fetch user info
            // the refresh token maybe expired or revoked
    }
}
// value can be NO_SESSION or AUTHENTICATED
// After authgear.configure, it only reflect SDK local state.
SessionState sessionState = authgear.getSessionState();

if (sessionState == SessionState.AUTHENTICATED) {
    authgear.fetchUserInfo(new OnFetchUserInfoListener() {
        @Override
        public void onFetchedUserInfo(@NonNull UserInfo userInfo) {
            // sessionState is now up to date
            // read the userInfo if needed
        }

        @Override
        public void onFetchingUserInfoFailed(@NonNull Throwable throwable) {
            // sessionState is now up to date
            // it will change to NO_SESSION if the session is invalid
        }
    });
}
// value can be NoSession or Authenticated
// After Authgear.ConfigureAsync, it only reflects local state.
var sessionState = authgear.SessionState;

if (sessionState == SessionState.Authenticated)
{
    try
    {
        var userInfo = await authgear.FetchUserInfoAsync();
        // sessionState is now up to date
    }
    catch (Exception ex)
    {
        // sessionState is now up to date
        // it will change to NoSession 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)

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}`
        };
    });
authgear.refreshAccessTokenIfNeeded() { result in
    switch result {
    case .success():
        // access token is ready to use
        // accessToken can be empty
        // it will be empty if user is not logged in or session is invalid

        // include Authorization header in your application request
        if let accessToken = authgear.accessToken {
            // example only, you can use your own networking library
            var urlRequest = URLRequest(url: "YOUR_SERVER_URL")
            urlRequest.setValue(
                "Bearer \(accessToken)", forHTTPHeaderField: "authorization")
            // ... continue making your request
        }
    case let .failure(error):
        // failed to refresh access token
        // the refresh token maybe expired or revoked
    }
}
// Suppose we are preparing an http request in a background thread.

// Setting up the request, e.g. preparing a URLConnection

try {
    authgear.refreshAccessTokenIfNeededSync();
} catch (OauthException e) {
    // failed to refresh access token
    // the refresh token maybe expired or revoked
}
// 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
String accessToken = authgear.getAccessToken();
HashMap<String, String> headers = new HashMap<>();
headers.put("authorization", "Bearer " + accessToken);

// Submit the request with the headers...
try
{
    await authgear.RefreshAccessTokenIfNeededAsync();
}
catch (OauthException ex)
{
    // failed to refresh access token
    // the refresh token maybe expired or revoked
}
// 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
var accessToken = authgear.AccessToken;
var client = GetHttpClient();  // Get the re-used http client of your app, as per recommendation.
var httpRequestMessage = new HttpRequestMessage(myHttpMethod, myUrl);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Send the request with the headers...

Handle revoked sessions

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");
    }
    // ...
}
// example only
// if your application server return HTTP status code 401 for unauthorized request
if let response = response as? HTTPURLResponse {
    if response.statusCode == 401 {

        // if you want to clear the session state locally, call clearSessionState
        // `authgear.sessionState` will become `.noSession` after calling
        authgear.clearSessionState { result in
            switch result {
            case .success():
                // clear SDK session state locally
                // `authgear.sessionState` becomes `.noSession`
            case let .failure(error):
                // failed to clear session state
            }
        }
    }
}
// example only
// if your application server return HTTP status code 401 for unauthorized request
responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.Unauthorized) {

    // if you want to clear the session state locally, call clearSessionState
    // `authgear.getSessionState()` will become `NO_SESSION` after calling
    authgear.clearSessionState();
}
// example only
// if your application server return HTTP status code 401 for unauthorized request
statusCode = httpResponseMessage.StatusCode;
if (statusCode == HttpStatusCode.Unauthorized)
{
    // if you want to clear the session state locally, call ClearSessionState
    // `authgear.SessionState` will become `NoSession` after calling
    authgear.ClearSessionState();
}

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 .

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 .

Backend integration
fetch
resolver headers