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
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.
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.
let authgear =Authgear(clientId: clientId, endpoint: endpoint)authgear.configure() { result inswitch result {case .success():// configured successfullycaselet .failure(error):// failed to configured }}
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.
// 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 validif authgear.sessionState == .authenticated { authgear.fetchUserInfo { userInfoResult in// sessionState is now up to date// it will change to .noSession if the session is invalidlet sessionState = authgear.sessionStateswitch userInfoResult {caselet .success(userInfo):// read the userInfo if neededcaselet .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(newOnFetchUserInfoListener() { @OverridepublicvoidonFetchedUserInfo(@NonNullUserInfo userInfo) {// sessionState is now up to date// read the userInfo if needed } @OverridepublicvoidonFetchingUserInfoFailed(@NonNullThrowable 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 =awaitauthgear.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 }}
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.
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 invalidconst accessToken =authgear.accessToken;// include Authorization header in your application requestconst headers = { Authorization: `Bearer ${accessToken}` }; });
authgear.refreshAccessTokenIfNeeded() { result inswitch 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 requestiflet accessToken = authgear.accessToken {// example only, you can use your own networking libraryvar urlRequest =URLRequest(url:"YOUR_SERVER_URL") urlRequest.setValue("Bearer \(accessToken)", forHTTPHeaderField:"authorization")// ... continue making your request }caselet .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 URLConnectiontry {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 invalidString accessToken =authgear.getAccessToken();HashMap<String,String> headers =newHashMap<>();headers.put("authorization","Bearer "+ accessToken);// Submit the request with the headers...
try{awaitauthgear.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 invalidvar accessToken =authgear.AccessToken;var client =GetHttpClient(); // Get the re-used http client of your app, as per recommendation.var httpRequestMessage =newHttpRequestMessage(myHttpMethod, myUrl);httpRequestMessage.Headers.Authorization=newAuthenticationHeaderValue("Bearer", accessToken);// Send the request with the headers...
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.
// example only// if your application server return HTTP status code 401 for unauthorized requestasyncfunctionfetchAppServer() {var response =awaitauthgear.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 callingawaitauthgear.clearSessionState();thrownewError("user session invalid"); }// ...}
// example only// if your application server return HTTP status code 401 for unauthorized requestiflet 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 inswitch result {case .success():// clear SDK session state locally// `authgear.sessionState` becomes `.noSession`caselet .failure(error):// failed to clear session state } } }}
// example only// if your application server return HTTP status code 401 for unauthorized requestresponseCode =httpConn.getResponseCode();if (responseCode ==HttpURLConnection.Unauthorized) {// if you want to clear the session state locally, call clearSessionState// `authgear.getSessionState()` will become `NO_SESSION` after callingauthgear.clearSessionState();}
// example only// if your application server return HTTP status code 401 for unauthorized requeststatusCode =httpResponseMessage.StatusCode;if (statusCode ==HttpStatusCode.Unauthorized){ // if you want to clear the session state locally, call ClearSessionState // `authgear.SessionState` will become `NoSession` after callingauthgear.ClearSessionState();}