Skip to content

Commit

Permalink
Add interactive quckstart for Xamarin (#10306)
Browse files Browse the repository at this point in the history
  • Loading branch information
frederikprijck committed Sep 22, 2023
1 parent 7883c18 commit f54ed40
Show file tree
Hide file tree
Showing 6 changed files with 372 additions and 3 deletions.
37 changes: 37 additions & 0 deletions articles/quickstart/native/xamarin/_configure_urls_interactive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
## Configure Auth0 {{{ data-action=configure }}}

To use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for your project.

### Configure an application

Use the interactive selector to create a new "Native Application", or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.

Any settings you configure using this quickstart will automatically update for your application in the <a href="${manage_url}/#/">Dashboard</a>, which is where you can manage your applications in the future.

If you would rather explore a complete configuration, you can view a sample application instead.

### Configure Callback URLs

A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in.

::: note
If you are following along with our sample project, set this to one of the following URLs, depending on your platform:

**Android**: `YOUR_PACKAGE_NAME://${account.namespace}/android/YOUR_PACKAGE_NAME/callback`

**iOS**: `YOUR_BUNDLE_ID://${account.namespace}/ios/YOUR_BUNDLE_ID/callback`
:::

### Configure Logout URLs

A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.

::: note
If you are following along with our sample project, set this to one of the following URLs, depending on your platform:

**Android**: `YOUR_PACKAGE_NAME://${account.namespace}/android/YOUR_PACKAGE_NAME/callback`

**iOS**: `YOUR_BUNDLE_ID://${account.namespace}/ios/YOUR_BUNDLE_ID/callback`
:::

Lastly, be sure that the **Application Type** for your application is set to **Native** in the [Application Settings](${manage_url}/#/applications/${account.clientId}/settings).
19 changes: 19 additions & 0 deletions articles/quickstart/native/xamarin/files/app-delegate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
name: AppDelegate.cs
language: csharp
---

```csharp
using Auth0.OidcClient;

[Register("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
ActivityMediator.Instance.Send(url.AbsoluteString);

return true;
}
}
```
57 changes: 57 additions & 0 deletions articles/quickstart/native/xamarin/files/main-activity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
---
name: MainActivity.cs
language: csharp
---

```csharp
// Example of a full Android Activity
[Activity(Label = "AndroidSample", MainLauncher = true, Icon = "@drawable/icon",
LaunchMode = LaunchMode.SingleTask)]
[IntentFilter(
new[] { Intent.ActionView },
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
DataScheme = "YOUR_ANDROID_PACKAGE_NAME",
DataHost = "{yourDomain}",
DataPathPrefix = "/android/YOUR_ANDROID_PACKAGE_NAME/callback")]
public class MainActivity : Activity
{
private Auth0Client _auth0Client;

protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
ActivityMediator.Instance.Send(intent.DataString);
}

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

Auth0ClientOptions clientOptions = new Auth0ClientOptions
{
Domain = "${account.namespace}"
ClientId = "${account.clientId}"
};

_auth0Client = new Auth0Client(clientOptions, this);
}

private async void LoginButtonOnClick(object sender, EventArgs eventArgs)
{
var loginResult = await _auth0Client.LoginAsync();

if (loginResult.IsError == false)
{
var user = loginResult.User;
var name = user.FindFirst(c => c.Type == "name")?.Value;
var email = user.FindFirst(c => c.Type == "email")?.Value;
var picture = user.FindFirst(c => c.Type == "picture")?.Value;
}
}

private async void LogoutButtonOnClick(object sender, EventArgs e)
{
await _auth0Client.LogoutAsync();
}
}
```
47 changes: 47 additions & 0 deletions articles/quickstart/native/xamarin/files/my-view-controller.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
name: MyViewController.cs
language: csharp
---

```csharp
// Example of a full iOS UIViewController
public partial class MyViewController : UIViewController
{
private Auth0Client _auth0Client;

public MyViewController() : base("MyViewController", null)
{
}

public override void ViewDidLoad()
{
base.ViewDidLoad();

Auth0ClientOptions clientOptions = new Auth0ClientOptions
{
Domain = "${account.namespace}"
ClientId = "${account.clientId}"
};

_auth0Client = new Auth0Client(clientOptions, this);
}

private async void LoginButton_TouchUpInside(object sender, EventArgs e)
{
var loginResult = await _auth0Client.LoginAsync();

if (loginResult.IsError == false)
{
var user = loginResult.User;
var name = user.FindFirst(c => c.Type == "name")?.Value;
var email = user.FindFirst(c => c.Type == "email")?.Value;
var picture = user.FindFirst(c => c.Type == "picture")?.Value;
}
}

private async void LogoutButton_TouchUpInside(object sender, EventArgs e)
{
await _auth0Client.LogoutAsync();
}
}
```
7 changes: 4 additions & 3 deletions articles/quickstart/native/xamarin/index.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ snippets:
setup: native-platforms/xamarin/setup
seo_alias: xamarin
default_article: 01-login
hidden_articles:
- interactive
articles:
- 01-login
show_steps: true
Expand All @@ -31,10 +33,9 @@ sdk:
url: https://github.com/auth0/auth0-oidc-client-net
logo: xamarin
requirements:
- Visual Studio 2017+ or Visual Studio for Mac
- Visual Studio 2022 or Visual Studio for Mac
- Xamarin for Visual Studio
- Auth0.OidcClient.Android 3.1.3
- Auth0.OidcClient.iOS 3.2.0
- .NET 6+
next_steps:
- path: 01-login
list:
Expand Down
208 changes: 208 additions & 0 deletions articles/quickstart/native/xamarin/interactive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
---
title: Add login to your .NET Android or iOS application
default: true
description: This tutorial demonstrates how to add user login with Auth0 to a .NET Android or iOS application.
budicon: 448
topics:
- quickstarts
- native
- xamarin
- dotnet
- android
- ios
github:
path: Quickstart/01-Login
contentType: tutorial
useCase: quickstart
interactive: true
files:
- files/main-activity
- files/app-delegate
- files/my-view-controller
---

# Add Login to .NET Android and iOS App

Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in any .NET Android and iOS application using the Auth0 SDKs for [Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/) and [iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS).

::: note
This quickstart focusses on .NET Android and iOS, as they are the next generation of `Xamarin.Android` and `Xamarin.iOS`. If you are still using `Xamarin.Android` and `Xamarin.iOS`, you can follow this guide as well as integration is identical and the SDKs are compatible.
:::

To use this quickstart, you’ll need to:

- Sign up for a free Auth0 account or log in to Auth0.
- Have a working Android or iOS project using .NET 6 (or above) that you want to integrate with. Alternatively, you can view or download a sample application after logging in.

<%= include('_configure_urls_interactive') %>

## Install the Auth0 SDK

Auth0 provides an [Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/) and [iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS) SDK to simplify the process of implementing Auth0 authentication in .NET Android and iOS applications.

Use the NuGet Package Manager (Tools -> Library Package Manager -> Package Manager Console) to install the `Auth0.OidcClient.AndroidX` or `Auth0.OidcClient.iOS` package, depending on whether you are building an Android or iOS application.

Alternatively, you can use the Nuget Package Manager Console (`Install-Package`) or the `dotnet` CLI (`dotnet add`).

```ps
Install-Package Auth0.OidcClient.AndroidX
Install-Package Auth0.OidcClient.iOS
```
```
dotnet add Auth0.OidcClient.AndroidX
dotnet add Auth0.OidcClient.iOS
```

## Instantiate the Auth0Client

To integrate Auth0 into your application, instantiate an instance of the `Auth0Client` class, passing an instance of `Auth0ClientOptions` that contains your Auth0 Domain and Client ID.

```csharp
using Auth0.OidcClient;

var client = new Auth0Client(new Auth0ClientOptions
{
Domain = "{yourDomain}",
ClientId = "{yourClientId}"
}, this);
```

By default, the SDK will leverage Chrome Custom Tabs for Android and ASWebAuthenticationSession for iOS.

::::checkpoint

:::checkpoint-default

Your `Auth0Client` should now be properly instantiated. Run your application to verify that:
- the `Auth0Client` is instantiated correctly in the `Activity` (Android) or `UIViewController` (iOS)
- your application is not throwing any errors related to Auth0

:::

:::checkpoint-failure
Sorry about that. Here are a couple things to double-check:
* make sure the correct application is selected
* did you save after entering your URLs?
* make sure the domain and client ID are imported correctly

Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.

:::
::::

## Configure Android {{{ data-action="code" data-code="MainActivity.cs#2-9,14-18" }}}

After a user successfully authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.

To handle the callback on Android devices, you need to register an intent that handles this callback URL. An easy way to do this is to register the intent on the same activity from which you called the LoginAsync method to instantiate the authentication flow.

Ensure to replace `YOUR_ANDROID_PACKAGE_NAME` in the code sample with the actual Package Name for your application, such as com.mycompany.myapplication, and ensure that all the text for the `DataScheme`, `DataHost`, and `DataPathPrefix` is in lower case. Also, set `LaunchMode = LaunchMode.SingleTask` for the Activity, otherwise the system will create a new instance of the activity every time the Callback URL gets called.

Additionally, you need to handle the intent in the `OnNewIntent` event in your `Activity` class. You need to notify the Auth0 OIDC Client to finish the authentication flow by calling the `Send` method of the `ActivityMediator` singleton, passing along the URL that was sent in.

## Configure iOS {{{ data-action="code" data-code="AppDelegate.cs#6-11" }}}

After a user successfully authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.

To handle the callback on iOS devices:

- Open your application's `Info.plist` file in Visual Studio, and go to the **Advanced** tab.
- Under **URL Types**, click the **Add URL Type** button
- Set the **Identifier** as Auth0, the **URL Schemes** the same as your application's Bundle Identifier, and the **Role** as None

This is an example of the XML representation of your `info.plist` file after you have added the URL Type:

```xml
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>None</string>
<key>CFBundleURLName</key>
<string>Auth0</string>
<key>CFBundleURLSchemes</key>
<array>
<string>YOUR_BUNDLE_IDENTIFIER</string>
</array>
</dict>
</array>
```

Additionally, you need to handle the Callback URL in the `OpenUrl` event in your `AppDelegate` class. You need to notify the Auth0 OIDC Client to finish the authentication flow by calling the `Send` method of the `ActivityMediator` singleton, passing along the URL that was sent in.

## Add Login to Your Application

Now that you have configured your Auth0 Application and the Auth0 SDK, you need to set up login for your project. To do this, you will use the SDK’s `LoginAsync()` method to create a login button that redirects users to the Auth0 Universal Login page.

```csharp
var loginResult = await client.LoginAsync();
```

If there isn't any error, you can access the `User`, `IdentityToken`, `AccessToken` and `RefreshToken` on the `LoginResult` returned from `LoginAsync()`.

::::checkpoint

:::checkpoint-default

You should now be able to log in or sign up using a username and password.

Click the login button and verify that:
* your Android or iOS application redirects you to the Auth0 Universal Login page
* you can log in or sign up
* Auth0 redirects you to your application.

:::

:::checkpoint-failure
Sorry about that. Here's something to double-check:
* you called `LoginAsync` as expected

Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.

:::
::::

## Add Logout to Your Application

Users who log in to your project will also need a way to log out. Create a logout button using the SDK’s `LogoutAsync()` method. When users log out, they will be redirected to your Auth0 logout endpoint, which will then immediately redirect them back to the logout URL you set up earlier in this quickstart.

```csharp
await client.LogoutAsync();
```

::::checkpoint

:::checkpoint-default

Run your application and click the logout button, verify that:
* your Android or iOS application redirects you to the address you specified as one of the Allowed Logout URLs in your Application Settings
* you are no longer logged in to your application

:::

:::checkpoint-failure
Sorry about that. Here are a couple things to double-check:
* you configured the correct Logout URL
* you called `LogoutAsync` as expected.

Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.

:::

::::

## Show User Profile Information

Now that your users can log in and log out, you will likely want to be able to retrieve the [profile information](https://auth0.com/docs/users/concepts/overview-user-profile) associated with authenticated users. For example, you may want to be able to display a logged-in user’s name or profile picture in your project.

The Auth0 SDK for Android and iOS provides user information through the `LoginResult.User` property.

```csharp
if (loginResult.IsError == false)
{
var user = loginResult.User;
var name = user.FindFirst(c => c.Type == "name")?.Value;
var email = user.FindFirst(c => c.Type == "email")?.Value;
var picture = user.FindFirst(c => c.Type == "picture")?.Value;
}
```

0 comments on commit f54ed40

Please sign in to comment.