#311: Include export users api in api reference doc page
Change request updated
This guide provides instructions on integrating Authgear with a Xamarin app. Supported packages include:
Xamarin.Essentials 1.7.2 or higher
Xamarin.Forms 5.0.0.2401 or higher
Setup Application in Authgear
Signup for an Authgear Portal account in https://portal.authgear.com/. Or you can use your self-deployed Authgear.
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
In your IDE (e.g. Visual Studio), define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path.[^1]
Head back to Authgear Portal, fill in the Redirect URI that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
Authgear.Xamarin targets MonoAndroid 12.0 on Android, and Xamarin.iOS10 on iOS. Update the target framework of the Android and iOS projects to match Authgear.Xamarin's target frameworks.
Update Android and iOS project's Xamarin.Essentials to 1.7.2.
Platform Integration
To finish the integration, setup the app to handle the redirectURI specified in the application. This part requires platform specific integration.
Targeting API level 30 or above (Android 11 or above)
If your Android app is targeting API level 30 or above (Android 11 or above), you need to add a queries section to AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"><!-- Other elements such <application> --> <queries> <intent> <actionandroid:name="android.support.customtabs.action.CustomTabsService" /> </intent> </queries></manifest>
Initialize a global AuthgearSdk instance
In your MainActivity.cs
usingSystem;usingAndroid.App;usingAndroid.Content.PM;usingAndroid.Runtime;usingAndroid.OS;usingXamarin.Forms;usingAuthgear.Xamarin;namespaceMyApp.Droid{publicclassMainActivity:global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {protectedoverridevoidOnCreate(Bundle savedInstanceState) { // ...var authgear =newAuthgearSdk(this,newAuthgearOptions { ClientId = CLIENT_ID, AuthgearEndpoint = ENDPOINT });DependencyService.RegisterSingleton<AuthgearSdk>(authgear);LoadApplication(newApp()); // ... } // other methods are omitted for brevity. }}
iOS
Add the following key-value pair in your iOS project Info.plist
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingXamarin.Forms;usingAuthgear.Xamarin;namespaceMyApp{publicpartialclassMainPage:ContentPage {privateAuthgearSdk authgear;publicMainPage() {InitializeComponent(); authgear =DependencyService.Get<AuthgearSdk>(); }asyncvoidConfigure_Clicked(object sender,EventArgs e) { // You must configure the instance before use. // Typically you should do this once on app launch.awaitauthgear.ConfigureAsync(); }asyncvoidAuthenticate_Clicked(object sender,EventArgs e) {var userInfo =awaitauthgear.AuthenticateAsync(newAuthenticateOptions { RedirectUri = REDIRECT_URI }); } }}
Get the Logged In State
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in). The SessionState reflects the user logged in state in the SDK locally on the device. That means even the SessionState is Authenticated, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call FetchUserInfoAsync to update the SessionState as soon as it is proper to do so.
// 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 }}
The value of SessionState can be Unknown, NoSession or Authenticated. Initially, the SessionState is Unknown. After a call to authgear.configure, the session state would become Authenticated if a previous session was found, or NoSession if such session was not found.
Fetching User Info
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the FetchUserInfoAsync function to obtain the user info, see example.
Logout
To log out the user from the current app session, you need to invoke thelogoutfunction.
awaitauthgear.LogoutAsync();
Calling An API
To include the access token to the HTTP requests to your application server, you set the bearer token manually by using authgear.AccessToken.
Using HttpClient
You can get the access token through authgear.AccessToken. Call RefreshAccessTokenIfNeededAsync every time before using the access token, the function will check and make the network call only if the access token has expired. Then, include the access token into the Authorization header of the http request.
awaitauthgear.RefreshAccessTokenIfNeededAsync();// 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);
Next steps
To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.