Xamarin.Forms – Login Flow APP

Authentication with xamarin forms and auth0

Most modern applications require users to verify their identity. Authentication is the process of verifying the identity of a user. If you want to implement authentication for your application from scratch, first you need to store your users information and credentials, then you need to start from the user sign up and implement all steps. In some cases, using a third-party authentication service can be a good idea to save time.

In this blog post, we will be using Auth0 as an authentication service. Auth0 is an authentication and Authorization service that implements OpenID Connect (OIDC) and OAuth 2.0 standards. You can sign up for Auth0 and create a free account from their website.


Things we will be doing:

Creating Web API

We will create a simple Web API that returns a static list of books and their authors. The default Web API template of ASP.NET Core is enough to complete this step. Using https can be painful while we are working in our local environment. To keep things simple and not to deal with SSL certificates in our local environment we will disable https redirection while we are creating our API project. If you want to use https in your local environment you can find more details in this article.

Xamarin.Forms - Login Flow APP

After creating the Web API project we only need to add a single controller and a single model.

When we run our API and go to http://localhost:5000/books, it should display the books in our browser window.

Our iOS simulator or Android emulator cannot resolve the web service from http://localhost if you are pairing your Windows machine with your Mac like me. We need to expose our service externally. To do that we are overriding our applicationUrls in launchSettings.json file.

Creating Xamarin Forms App

We will use Xamarin Forms flyout template for this sample application. We will create a new project in Visual Studio.

Xamarin.Forms - Login Flow APP

And choose flyout template like below.

Xamarin.Forms - Login Flow APP

Adding Books Page to Xamarin App

Before we add our new page to the mobile application, we will create a Book model under the models folder in our core Xamarin project to deserialize the response from our API.

And also, we will add BooksViewModel to our core Xamarin project. This view model will be responsible for the API calls. We will add the Newtonsoft.Json package via NuGet to all our projects so we can deserialize JSON responses from our API.

As you can see in the above snippet, I am using my computer’s IP address to consume the API. Please do not forget to change that with your machine’s IP address.

Now it is time to add our new books page to our application. First, we are creating a new BooksPage under Views folder like below.

Xamarin.Forms - Login Flow APP

Let’s add our books list to the new books page.

Last step that we need to do is adding our new page to flyout and tab menu in the application. We will open AppShell.xaml file and add the books page to flyout items.

Похожее:  Делаем красивую форму на HTML и CSS. | LinuxBlog.РФ

Now we are ready for testing. When we run our API and mobile apps we should see the books list.

Xamarin.Forms - Login Flow APP

Protecting Web Api with Auth0

Great, we can consume our API from mobile apps now. But we do not want to view our super-secret books list by unauthorized users. We are lucky because it is an easy task to do with Auth0. We will go to our Auth0 dashboard, and open the APIs page from the left side menu, and we will create a new API.

Xamarin.Forms - Login Flow APP

Your identifier name can be any url, as mentioned in the new api form Auth0 won’t use your identifier to call your Web API. After we created our new API in Auth0 we can find all the information that we need to use for JWT token validation under the API settings.

Xamarin.Forms - Login Flow APP

We need to go back to our API project and add Microsoft.AspNetCore.Authentication.JwtBearer library via NuGet and then we will modify our startup.cs file and will add authorize attribute to the get action inside BookController.

After this point only the authorized users with a valid access token can call our API. If you run the API and try again to browse it with the browser you will get a 401 unauthorized error code. It will be the same for the mobile applications.

Creating Client App

We will go back to Auth0 dashboard to define our Xamarin app as a client application which has access rights to our API. Users can only login via a valid client. To add our new application, we are selecting Applications from left side menu and clicking to Create Application button.

Xamarin.Forms - Login Flow APP

We need to choose native application type for our Xamarin forms application. We can find the client settings which we need to make login request from our application settings. To finish our application setup we will define our callback urls.  In application settings, there are 2 text boxes which accept the allowed callback and logout URLs.

Allowed callback urls

For iOS : {package-name}//{your-auth0-domain}/ios/{package-name}/callback
For Android: {package-name}://{your-auth0-domain}/android/{package-name}/callback

Allowed Logout URLs

For iOS: {package-name}://{your-auth0-domain}/ios/{package-name}/callback
For Android: {package-name}://{your-auth0-domain}/android/{package-name}/callback

Our package name should look like “com.companyname.someapp” and our auth0 domain should look like “dev-myauth.au.auth0.com” We will save our last changes and complete minimum requirements in our Auth0 setup. Let’s go and add login to Xamarin app.

Add Login to Xamarin App

We will create an auth folder under our core Xamarin project to keep our authentication helper classes. We will need our client settings for making the login request to Auth0. To keep them we will add new AuthConfig class under our new auth folder.

Auth0 use different clients for Android and iOS platforms because of that we need a common authentication result class to reach the authentication result, which contains needed tokens and user claims, from core Xamarin project. Let’s add our new AuthenticationResult.cs to auth folder.

Похожее:  Смс авторизация на сайте (регистрация через смс) или генератор паролей для смс, восстановление пароля по смс

Then we will create IAuthService interface. This interface will be implemented in iOS and Android projects and used by the shared Xamarin project.


First we will add Auth0.OidcClient.iOS library via NuGet to our iOS project. Then we will add AuthService class to our iOS project. For simplicity, we will use DependencyService from Xamarin forms to call our AuthService from our Xamarin core project. In a real world application using a third party IoC container might be a better idea.

To be able to log in with Auth0 through SFSafariViewController we have to add CFBundleURLTypes to our info.plist

Xamarin.Forms - Login Flow APP

And also we will activate keychain because we will store our access token in secure storge.

Xamarin.Forms - Login Flow APP

Entitlement.plist file should be added to custom entitlements in our ios.bundle.signing settings.

Xamarin.Forms - Login Flow APP

Finally, we override the OpenUrl method inside AppDelegage.cs to handle Auth0 callback.

We use ActivityMediator Send method to complete the login request process.


First we will add Auth0.OidcClient.Android library via NuGet to our Android project. Then we will implement AuthService in Android project.

Now we need to add IntentFilter to MainActivity class so the application knows login request completed.

Login with Xamarin Forms

It is time to log in from our app to be able to call our API. The flyout template which we used to create our application already has a login page and viewmodel. Let’s modify those files to trigger Auth0 login.

In here we are using our auth service which we implemented in both platforms to trigger Auth0 login process. After we logged in we are storing user’s access token in secure storage to use it for our api calls.

Before we start to modify our login page, we will add a new converter to our project to be able to show and hide log in and log out buttons, which we will add our profile page. We will create a new converters folder in our core Xamarin project and will add below class.

We are ready to modify our login page.

At that point we can run our application and if we choose the last item (In my screen shots it is profile. If you didn’t change the default template it can logout in your environment) from the flyout menu Auth0 login process will be triggered.

Xamarin.Forms - Login Flow APP

We can signup from opened web page and complete our account creation by verifying our email. After we signup we still won’t be able to see the books list because we didn’t pass our access token to our API yet.

Calling Web Api With Access Token

Our last step is getting our access token from secure storage and add it to our requests header. To do that we will go back to our BooksViewModel and modify the ExecuteLoadBooksCommand method.

Похожее:  Личный кабинет Мегафон Сервис Гид - регистрация и вход по номеру телефона

After we made the last changes now we can view our books list after we loggedin. And also, We can logout by using profile page.


We got a head start to Auth0 with this blog post. This is just a tip of the iceberg. Auth0 is highly customisable service. You can restyle from login page to verification mail in Auth0.

You might save a lot of time by not reinventing the wheel. Auth0 is a complete solution which handles all complexity of authentication process.


Для того, чтобы работать с OAuth в Xamarin мы остановимся на простой и удобной библиотеке Xamarin.Auth, которая развивается уже не первый год и имеет все необходимые для нас механизмы:

Также Xamarin.Auth поддерживает возможность хранения учетных данных пользователя в защищенном хранилище. В общем, зрелый и качественный компонент с необходимой функциональностью.

Рекомендуем устанавливать Xamarin.Auth из Nuget, так как версия в Xamarin Components уже давно устарела и не обновляется.

Xamarin.forms – login flow app


This article demonstrates how to manipulate the navigation stack panel in order to only display the main page of the application once the user has successfully logged in.

Let’s start.

Select CrossPlatform App(Xamarin.Forms or Native) and give the application a suitable name, such as Login_Flow.

In the popup window, select Cross platform>>Empty XAML page. Give the page name as SignupPage.xaml. This page is your application signup page.

In this popup window, select Cross Platform>>class. Give the class a name like User.

Xamarin: авторизация oauth для xamarin-приложений

Восьмая статья в цикле “Рецепты для Xamarin-разработчиков”.

Подключаем авторизацию в pcl

На уровне PCL все как обычно — делаем простой интерфейс IOAuthService для платформенного сервиса, никаких новых зависимостей в проект не добавляем.

Task<LoginResult> Login();

Ну и, конечно же, будет необходимо добавить обращение к методам DependencyService.Get<IOAuthService>().Login() и DependencyService.Get<IOAuthService>().Logout() внутри нашей страницы авторизации.

Также нет проблем добавить поддержку нескольких OAuth-сервисов. Для этого можно добавить в методы Login() и Logout() аргумент providerName (тип string, int или enum) и в зависимости от его значения выбирать поставщика услуг.

Реализация платформенной части

Как уже отмечалось ранее, необходимо добавить библиотеки Xamarin.Auth из Nuget в каждый платформенный проект, в нашем случае — iOS и Android. Дальше пишем нашу реализацию IOAuthService для каждой платформы и регистрируем ее в качестве Dependency.

Теперь нам достаточно создать экземпляр класса OAuth2Authenticator с нужными параметрами:


Сегодня мы завершили рассмотрение всех популярных способов авторизации пользователей и получения базовой информации о них через внешние сервисы. Описанные механизмы подходят как для Xamarin.Forms, так и для классического Xamarin iOS/Android. Полные исходные коды проекта со всеми примерами можно найти в нашем репозитории:

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 4,00 из 5)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *