From 0718e6b39040fef235a7c3bea1175de71679e89f Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 16:52:16 +0800 Subject: [PATCH 01/17] Add session state example in xamarin getting started #78 --- get-started/xamarin.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/get-started/xamarin.md b/get-started/xamarin.md index b5087c6..a1c2737 100644 --- a/get-started/xamarin.md +++ b/get-started/xamarin.md @@ -265,6 +265,30 @@ namespace MyApp } ``` +## Get the Logged In State + +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. + +```csharp +// 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 + } +} +``` + ## Logout To log out the user from the current app session, you need to invoke the`logout`function. From 122feb7a2a21d11def9291e2f22d6e7b79c801ca Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 17:20:57 +0800 Subject: [PATCH 02/17] Add token usage example in xamarin getting started #78 --- get-started/xamarin.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/get-started/xamarin.md b/get-started/xamarin.md index a1c2737..81bbd97 100644 --- a/get-started/xamarin.md +++ b/get-started/xamarin.md @@ -297,6 +297,25 @@ To log out the user from the current app session, you need to invoke the`logout` await authgear.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. + +```csharp +await authgear.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 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); +``` + ## Next steps To protect your application server from unauthorized access. You will need to **integrate your backend with Authgear**. From 72e5bff784844919f4cee407fa0c82557cabe019 Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 18:19:35 +0800 Subject: [PATCH 03/17] Add doc for biometric xamarin #78 --- strategies/biometric.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/strategies/biometric.md b/strategies/biometric.md index 163c3d2..ee12acb 100644 --- a/strategies/biometric.md +++ b/strategies/biometric.md @@ -128,6 +128,32 @@ try { ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +// We will need the options for the other biometric api +var ios = new BiometricOptionsIos { + LocalizedReason = "Use biometric to authenticate", + Constraint = BiometricAccessConstraintIos.BiometryAny, +}; +var android = new BiometricOptionsAndroid { + Title = "Biometric Authentication", + Subtitle = "Biometric authentication", + Description = "Use biometric to authenticate", + NegativeButtonText = "Cancel", + Constraint = BiometricAccessConstraintAndroid.BiometricOnly, + InvalidatedByBiometricEnrollment = false, +}; + +try { + // check if current device supports biometric login + await authgear.checkBiometricSupported(ios: ios, android: android); + // biometric login is supported +} catch (e) { + // biometric login is not supported +} +``` +{% endtab %} + {% endtabs %} * Enable biometric login for logged in user From adeaabb076071bd73afede023aa8b01eae556587 Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 20:19:49 +0800 Subject: [PATCH 04/17] Add xamarin to biometric doc #78 --- strategies/biometric.md | 106 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 2 deletions(-) diff --git a/strategies/biometric.md b/strategies/biometric.md index ee12acb..6916053 100644 --- a/strategies/biometric.md +++ b/strategies/biometric.md @@ -143,10 +143,13 @@ var android = new BiometricOptionsAndroid { Constraint = BiometricAccessConstraintAndroid.BiometricOnly, InvalidatedByBiometricEnrollment = false, }; - +var biometricOptions = new BiometricOptions { + Ios = ios, + Android = android +}; try { // check if current device supports biometric login - await authgear.checkBiometricSupported(ios: ios, android: android); + authgear.EnsureBiometricIsSupported(biometricOptions); // biometric login is supported } catch (e) { // biometric login is not supported @@ -228,6 +231,20 @@ try { } ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +try +{ + await authgear.EnableBiometricAsync(biometricOptions); + // enabled biometric login successfully +} +catch +{ + // failed to enable biometric with error +} +``` +{% endtab %} {% endtabs %} * Check if the current device enabled biometric login, we should check this before asking the user to log in with biometric credentials @@ -271,6 +288,21 @@ try { } ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +try +{ + var enabled = await authgear.GetIsBiometricEnabledAsync(); + // show if biometric login is enabled +} +catch +{ + // failed to check the enabled status +} +``` +{% endtab %} + {% endtabs %} * Login with biometric credentials @@ -332,6 +364,20 @@ try { } ``` {% endtab %} + +{% tab title="Xamrin" %} +```csharp +try +{ + var userInfo = await authgear.AuthenticateBiometricAsync(biometricOptions); + // logged in successfully +} +catch +{ + // failed to login +} +``` +{% endtab %} {% endtabs %} * Disable biometric login in the current device @@ -382,6 +428,21 @@ try { } ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +try +{ + await authgear.DisableBiometricAsync(); + // disabled biometric login successfully +} +catch +{ + // failed to disable biometric login +} +``` +{% endtab %} + {% endtabs %} * Error handling @@ -502,5 +563,46 @@ try { ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +try +{ + // ... +} +catch (OperationCanceledException ex) +{ + // user cancel +} +catch (BiometricPrivateKeyNotFoundException ex) +{ + // biometric info has changed. e.g. Touch ID or Face ID has changed. + // user have to set up biometric authentication again +} +catch (BiometricNoEnrollmentException ex) +{ + // device does not have biometric set up + // e.g. have not set up Face ID or Touch ID in the device +} +catch (BiometricNotSupportedOrPermissionDeniedException ex) +{ + // biometric is not supported in the current device + // or user has denied the permission of using Face ID +} +catch (BiometricNoPasscodeException ex) +{ + // device does not have unlock credential or passcode set up +} +catch (BiometricLockoutException ex) +{ + // the biometric is locked out due to too many failed attempts +} +catch +{ + // other error + // you may consider showing a generic error message to the user +} +``` +{% endtab %} + {% endtabs %} From 48a3cf749c878cce015bcbdac63603e93637a711 Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 20:28:14 +0800 Subject: [PATCH 05/17] Add xamarin in authvUI #78 --- integrate/auth-ui.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/integrate/auth-ui.md b/integrate/auth-ui.md index 6332fc5..75eda53 100644 --- a/integrate/auth-ui.md +++ b/integrate/auth-ui.md @@ -68,6 +68,15 @@ Future onPressOpenSettingsPage() async { ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +async void OnOpenSettingsClicked(object sender, EventArgs args) +{ + await authgear.OpenAsync(SettingsPage.Settings); +} +``` +{% endtab %} + {% tab title="iOS" %} ```swift func onPressOpenSettingsPage(sender: UIButton, forEvent event: UIEvent) { From 212af31620cdb9b2d661a2aafee2943b10f659d2 Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 21:01:37 +0800 Subject: [PATCH 06/17] Add xamarin to reauthenticate #78 --- integrate/reauthentication.md | 78 +++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/integrate/reauthentication.md b/integrate/reauthentication.md index 2a063cc..dff1fd5 100644 --- a/integrate/reauthentication.md +++ b/integrate/reauthentication.md @@ -130,6 +130,62 @@ Future onClickPerformSensitiveOperation() async { ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +var ios = new BiometricOptionsIos { + LocalizedReason = "Use biometric to authenticate", + AccessConstraint = BiometricAccessConstraintIos.BiometryAny, +}; +var android = new BiometricOptionsAndroid { + Title = "Biometric Authentication", + Subtitle = "Biometric authentication", + Description = "Use biometric to authenticate", + NegativeButtonText = "Cancel", + AccessConstraint = BiometricAccessConstraintAndroid.BiometricOnly, + InvalidatedByBiometricEnrollment = false, +}; + +async void OnPerformSensitiveOperationClicked(object sender, EventArgs args) +{ + // Step 1: Refresh the ID token to ensure the claims are up-to-date. + await authgear.RefreshIdTokenAsync(); + + // Step 2: Check if the end-user can be reauthenticated. + var canReauthenticate = authgear.CanReauthenticate; + if (!canReauthenticate) + { + // Step 2.1: Depending on your business need, you may want to allow + // the end-user to proceed. + // Here we assume you want to proceed. + var idTokenHint = authgear.IdTokenHint; + + // Step 2.2: Call the sensitive endpoint with the ID token. + // It is still required to pass the ID token to the endpoint so that + // the endpoint can know the end-user CANNOT be reauthenticated. + await CallMySensitiveEndpointAsync(idTokenHint); + return; + } + + // Step 3: The end-user can be reauthenticated. + // If your app supports biometric authentication, you can pass + // the biometric options to reauthenticate. + // If biometric is enabled for the current user, it will be used instead. + await authgear.ReauthenticateAsync(new ReauthenticateOptions + { + redirectURI: THE_REDIRECT_URI, + }, new BiometricOptions { + Ios = ios, + Android = android, + }); + + // Step 4: If we reach here, the reauthentication was done. + // The ID token have up-to-date auth_time claim. + var idTokenHint = authgear.IdTokenHint; + await CallMySensitiveEndpointAsync(idTokenHint); +} +``` +{% endtab %} + {% tab title="Web" %} ```typescript async function onClickPerformSensitiveOperation() { @@ -358,6 +414,28 @@ public void onClickPerformSensitiveOperation() { } ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +public async void OnPerformSensitiveOperationClicked(object sender, EventArgs args) +{ + await authgear.RefreshIdTokenAsync(); + var authTime = authgear.AuthTime; + if (authTime != null) + { + var now = DateTimeOffset.UtcNow; + var timedelta = now - authTime.Value; + if (timedelta < TimeSpan.FromSeconds(5)) + { + var idTokenHint = authgear.IdTokenHint; + callMySensitiveEndpoint(idTokenHint); + return; + } + } +} +``` +{% endtab %} + {% endtabs %} ## Backend Integration From 1c558e655e2577cd01e05c3b74a8e9e8cf71ef0a Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 21:19:58 +0800 Subject: [PATCH 07/17] Fix xamarin in biometric #78 --- strategies/biometric.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/strategies/biometric.md b/strategies/biometric.md index 6916053..f57309d 100644 --- a/strategies/biometric.md +++ b/strategies/biometric.md @@ -131,27 +131,33 @@ try { {% tab title="Xamarin" %} ```csharp // We will need the options for the other biometric api -var ios = new BiometricOptionsIos { +var ios = new BiometricOptionsIos +{ LocalizedReason = "Use biometric to authenticate", - Constraint = BiometricAccessConstraintIos.BiometryAny, + AccessConstraint = BiometricAccessConstraintIos.BiometricAny, }; -var android = new BiometricOptionsAndroid { +var android = new BiometricOptionsAndroid +{ Title = "Biometric Authentication", Subtitle = "Biometric authentication", Description = "Use biometric to authenticate", NegativeButtonText = "Cancel", - Constraint = BiometricAccessConstraintAndroid.BiometricOnly, + AccessConstraint = BiometricAccessConstraintAndroid.BiometricOnly, InvalidatedByBiometricEnrollment = false, }; -var biometricOptions = new BiometricOptions { +var biometricOptions = new BiometricOptions +{ Ios = ios, Android = android }; -try { +try +{ // check if current device supports biometric login authgear.EnsureBiometricIsSupported(biometricOptions); // biometric login is supported -} catch (e) { +} +catch +{ // biometric login is not supported } ``` From 016f678dadf6886f640c590b00dc9154a68428bc Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 21:21:44 +0800 Subject: [PATCH 08/17] Add xamarin in single-sign-on #78 --- integrate/single-sign-on.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/integrate/single-sign-on.md b/integrate/single-sign-on.md index f23c72f..9e6cc79 100644 --- a/integrate/single-sign-on.md +++ b/integrate/single-sign-on.md @@ -34,6 +34,17 @@ final authgear = Authgear( ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +var authgear = new AuthgearSdk(new AuthgearOptions +{ + ClientId = CLIENT_ID, + AuthgearEndpoint = ENDPOINT, + ShareSessionWithSystemBrowser = true, +}); +``` +{% endtab %} + {% tab title="iOS" %} ```swift Authgear( From 74af6684e1492dfef3edf67d666e6e6bf2c272b9 Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 21:25:09 +0800 Subject: [PATCH 09/17] Add xamarin in force-auth-app-launch #78 --- integrate/force-authentication-on-app-launch.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/integrate/force-authentication-on-app-launch.md b/integrate/force-authentication-on-app-launch.md index 749207d..a6f0cf5 100644 --- a/integrate/force-authentication-on-app-launch.md +++ b/integrate/force-authentication-on-app-launch.md @@ -29,6 +29,17 @@ final authgear = Authgear( ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +var authgear = new AuthgearSdk(new AuthgearOptions +{ + ClientId = CLIENT_ID, + AuthgearEndpoint = ENDPOINT, + TokenStorage: new TransientTokenStorage(), +}); +``` +{% endtab %} + {% tab title="iOS" %} ```swift Authgear( From b2a86a72914aeb66dcb2badb45655224384c46e0 Mon Sep 17 00:00:00 2001 From: Roxk Date: Thu, 19 May 2022 21:25:21 +0800 Subject: [PATCH 10/17] Fix xamarin in reauthentication #78 --- integrate/reauthentication.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/integrate/reauthentication.md b/integrate/reauthentication.md index dff1fd5..0ada9a7 100644 --- a/integrate/reauthentication.md +++ b/integrate/reauthentication.md @@ -132,11 +132,13 @@ Future onClickPerformSensitiveOperation() async { {% tab title="Xamarin" %} ```csharp -var ios = new BiometricOptionsIos { +var ios = new BiometricOptionsIos +{ LocalizedReason = "Use biometric to authenticate", - AccessConstraint = BiometricAccessConstraintIos.BiometryAny, + AccessConstraint = BiometricAccessConstraintIos.BiometricAny, }; -var android = new BiometricOptionsAndroid { +var android = new BiometricOptionsAndroid +{ Title = "Biometric Authentication", Subtitle = "Biometric authentication", Description = "Use biometric to authenticate", @@ -172,8 +174,9 @@ async void OnPerformSensitiveOperationClicked(object sender, EventArgs args) // If biometric is enabled for the current user, it will be used instead. await authgear.ReauthenticateAsync(new ReauthenticateOptions { - redirectURI: THE_REDIRECT_URI, - }, new BiometricOptions { + RedirectURI: THE_REDIRECT_URI, + }, new BiometricOptions + { Ios = ios, Android = android, }); @@ -425,7 +428,7 @@ public async void OnPerformSensitiveOperationClicked(object sender, EventArgs ar { var now = DateTimeOffset.UtcNow; var timedelta = now - authTime.Value; - if (timedelta < TimeSpan.FromSeconds(5)) + if (timedelta < TimeSpan.FromMinutes(5)) { var idTokenHint = authgear.IdTokenHint; callMySensitiveEndpoint(idTokenHint); From f07782bbdb2997fc9fb255b9025ac17a6125dbca Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 12:36:13 +0800 Subject: [PATCH 11/17] Fix platform-specific constructor for xamarin #78 --- integrate/force-authentication-on-app-launch.md | 11 +++++++++-- integrate/single-sign-on.md | 14 ++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/integrate/force-authentication-on-app-launch.md b/integrate/force-authentication-on-app-launch.md index a6f0cf5..4a5e3f8 100644 --- a/integrate/force-authentication-on-app-launch.md +++ b/integrate/force-authentication-on-app-launch.md @@ -31,12 +31,19 @@ final authgear = Authgear( {% tab title="Xamarin" %} ```csharp -var authgear = new AuthgearSdk(new AuthgearOptions +var authgearOptions = new AuthgearOptions { ClientId = CLIENT_ID, AuthgearEndpoint = ENDPOINT, TokenStorage: new TransientTokenStorage(), -}); +}; +#if __ANDROID__ +var authgear = new AuthgearSdk(GetActivity().ApplicationContext, authgearOptions); +#else +#if __IOS__ +var authgear = new AuthgearSdk(UIKit.UIApplication.SharedApplication, authgearOptions); +#endif +#endif ``` {% endtab %} diff --git a/integrate/single-sign-on.md b/integrate/single-sign-on.md index 9e6cc79..d3f0a4d 100644 --- a/integrate/single-sign-on.md +++ b/integrate/single-sign-on.md @@ -36,12 +36,22 @@ final authgear = Authgear( {% tab title="Xamarin" %} ```csharp -var authgear = new AuthgearSdk(new AuthgearOptions +var authgearOptions = new AuthgearOptions { ClientId = CLIENT_ID, AuthgearEndpoint = ENDPOINT, ShareSessionWithSystemBrowser = true, -}); +}; +// Android +#if __ANDROID__ +var activity = GetActivity(); +var authgear = new AuthgearSdk(activity.ApplicationContext, authgearOptions); +#else +#if __IOS__ +// iOS +var authgear = new AuthgearSdk(UIKit.UIApplication.SharedApplication, authgearOptions); +#endif +#endif ``` {% endtab %} From d5593a12f652bb7dbf2fa417edf7127a13fa5a1d Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 12:47:59 +0800 Subject: [PATCH 12/17] Add link for both flutter and xamarin #78 --- get-started/authentication-approach/token-based.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/get-started/authentication-approach/token-based.md b/get-started/authentication-approach/token-based.md index 5779f78..72d391b 100644 --- a/get-started/authentication-approach/token-based.md +++ b/get-started/authentication-approach/token-based.md @@ -46,6 +46,10 @@ Choose your platform below: {% page-ref page="../ios.md" %} +{% page-ref page="../flutter/" %} + +{% page-ref page="../xamarin.md" %} + ### 2. Backend Integration {% page-ref page="../backend-integration/" %} From 218382fbd2233bf0c1444a1b0aae218372f0ee8e Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 12:52:46 +0800 Subject: [PATCH 13/17] Unify platform specific constructor code #78 --- integrate/single-sign-on.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/integrate/single-sign-on.md b/integrate/single-sign-on.md index d3f0a4d..b7acb72 100644 --- a/integrate/single-sign-on.md +++ b/integrate/single-sign-on.md @@ -44,11 +44,9 @@ var authgearOptions = new AuthgearOptions }; // Android #if __ANDROID__ -var activity = GetActivity(); -var authgear = new AuthgearSdk(activity.ApplicationContext, authgearOptions); +var authgear = new AuthgearSdk(GetActivity().ApplicationContext, authgearOptions); #else #if __IOS__ -// iOS var authgear = new AuthgearSdk(UIKit.UIApplication.SharedApplication, authgearOptions); #endif #endif From b9eb626979a7d30b248f9718068733fa55c45b8b Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 12:54:31 +0800 Subject: [PATCH 14/17] Add xamarin in account deletion #78 --- integrate/account-deletion.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/integrate/account-deletion.md b/integrate/account-deletion.md index d4136f6..bff2ef1 100644 --- a/integrate/account-deletion.md +++ b/integrate/account-deletion.md @@ -39,6 +39,15 @@ await authgear.getUserInfo(); ``` {% endtab %} +{% tab title="Xamarin" %} +```csharp +// This method blocks until the user closes User Settings. +await authgear.OpenAsync(SettingsPage.Settings); +// One way to verify the validity of the session is to get User Info once. +await authgear.FetchUserInfoAsync(); +``` +{% endtab %} + {% endtabs %} ## Deactivated User From 7d8654a3d96e45d131914b4723c8232f1186af32 Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 12:59:05 +0800 Subject: [PATCH 15/17] Add xamarin in user profile #78 --- integrate/user-profile.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/integrate/user-profile.md b/integrate/user-profile.md index 15a3b62..97c44b2 100644 --- a/integrate/user-profile.md +++ b/integrate/user-profile.md @@ -60,6 +60,21 @@ authgear.fetchUserInfo(new OnFetchUserInfoListener() { }); ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +try +{ + var userInfo = await authgear.FetchUserInfoAsync() +} +catch +{ + // failed to fetch user info + // the refresh token maybe expired or revoked +} +``` +{% endtab %} + {% endtabs %} ## Standard Attributes From c1e3d3064f428de96a12fe8e78b988350d73bf99 Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 13:16:49 +0800 Subject: [PATCH 16/17] Add xamarin in use-sdk #78 --- ...ing-sdk-to-call-your-application-server.md | 97 +++++++++++++++++-- 1 file changed, 87 insertions(+), 10 deletions(-) diff --git a/integrate/using-sdk-to-call-your-application-server.md b/integrate/using-sdk-to-call-your-application-server.md index 0ea81f4..af6f3f8 100644 --- a/integrate/using-sdk-to-call-your-application-server.md +++ b/integrate/using-sdk-to-call-your-application-server.md @@ -71,6 +71,25 @@ authgear.configure(configureOptions, new OnConfigureListener() { }); ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +var authgearOptions = new AuthgearOptions +{ + ClientId = "", + AuthgearEndpoint: "", +}; +#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(); +``` +{% endtab %} + {% endtabs %} ### Get the latest session state @@ -146,6 +165,29 @@ if (sessionState == SessionState.AUTHENTICATED) { } ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +// 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 + } +} +``` +{% endtab %} + {% endtabs %} ## Calling an API @@ -222,22 +264,42 @@ authgear.refreshAccessTokenIfNeeded() { result in try { authgear.refreshAccessTokenIfNeededSync(); } catch (OauthException e) { - // The token is expired. + // 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(); -if (accessToken == null) { - // The user is not logged in, or the token is expired. - // It is up to the caller to decide how to handle this situation. Typically, the request could be aborted - // immediately as the response would be 401 anyways. - return; -} - HashMap headers = new HashMap<>(); headers.put("authorization", "Bearer " + accessToken); // Submit the request with the headers... ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +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... +``` +{% endtab %} + {% endtabs %} ### Handle revoked sessions @@ -293,13 +355,28 @@ if let response = response as? HTTPURLResponse { // example only // if your application server return HTTP status code 401 for unauthorized request responseCode = httpConn.getResponseCode(); -if (responseCode != HttpURLConnection.Unauthorized) { +if (responseCode == HttpURLConnection.Unauthorized) { // if you want to clear the session state locally, call clearSessionState - // ` authgear.getSessionState()` will become `NO_SESSION` after calling + // `authgear.getSessionState()` will become `NO_SESSION` after calling authgear.clearSessionState(); } ``` {% endtab %} + +{% tab title="Xamarin" %} +```csharp +// 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(); +} +``` +{% endtab %} + {% endtabs %} From 06e4911cb6505698a8831cb1c3fafa9bde58cd3a Mon Sep 17 00:00:00 2001 From: Roxk Date: Fri, 20 May 2022 13:23:47 +0800 Subject: [PATCH 17/17] Fix flutter link #78 --- get-started/authentication-approach/token-based.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/get-started/authentication-approach/token-based.md b/get-started/authentication-approach/token-based.md index 72d391b..e86b0ee 100644 --- a/get-started/authentication-approach/token-based.md +++ b/get-started/authentication-approach/token-based.md @@ -46,7 +46,7 @@ Choose your platform below: {% page-ref page="../ios.md" %} -{% page-ref page="../flutter/" %} +{% page-ref page="../flutter.md" %} {% page-ref page="../xamarin.md" %}