GitHub – xamarin/Xamarin.Auth: Xamarin.Auth

1 Creating Login UI

Now, the login UI can be obtained using GetUI() method and afterwards login screen is
ready to be presented.

The GetUI() method returns:

  • UINavigationController on iOS, and
  • Intent on Android.
  • System.Type on WinRT (Windows 8.1 and Windows Phone 8.1)
  • System.Uri on Windows Phone 8.x Silverlight

Android:

iOS:

3 present/launch the login ui

This step is platform specific and it is almost impossible to share it across platforms.

3 Retrieve stored accounts

Fetching all Account objects stored for a given service is possible with following API:

Retrieving accounts on Android:

Retrieving accounts on iOS:

It’s that easy.

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.

Overview

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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

And choose flyout template like below.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

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.

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

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth


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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth


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.

iOS

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

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth

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

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth


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

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth


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

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

Android

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.

GitHub - xamarin/Xamarin.Auth: Xamarin.Auth


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.

Conclusion

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.
 

Building

MacOSX

Windows:

Current version and status

  • nuget version 1.7.0
    • fixed issues:
      *
    • Removed old legacy platforms

Change Log

Documentation – github wiki pages

These are working docs and are copied to Wiki pages of the repo.

./docs/readme.md

[WORK IN PROGRESS]

./docs/readme-detailed.md

Installation

Xamarin.Auth can be installed in binary form (compiled and packaged)
or compiled from source.

Binary form is deployable as a NuGet from nuget.org or Xamarin Component
from component store:

  • NuGet
  • Component [UPDATE IN PROGRESS]

More details about how to compile Xamarin.Auth library and samples can be found in the docs
in repository on GitHub.

Oauth2 authorization code grant flow

With parameters:

OAuth details and how Xamarin.Auth implements OAuth is described in documentation in
Xamarin.Auth repo.

Oauth2 implicit grant flow

With parameters:

Status

CI servers:

Xamarin.Auth has grown into fully fledged cross platform library supporting:

  • Xamarin.Android
  • Xamarin.iOS (Unified only, Classic Support is removed)
  • Windows Phone Silverlight 8 (8.1 redundant)
  • Windows Store 8.1 WinRT
  • Windows Phone 8.1 WinRT
  • Universal Windows Platform (UWP)

Xamarin chat – community slack team (xamarin-auth-social room)

For those that need real-time help (hand-in-hand leading through implementation) the
best option is to use community slack channel. There are numerous people that have
implemented Xamarin.Auth with Native UI and maintainers/developers of the library.

1 client side initialization

Client (mobile) application initialization is based on OAuth Grant (flow) in use which is
determined by OAuth provider and it’s server side setup.

Initialization is performed through Authenticator constructors for:

Похожее:  Создание и управление пользователями Windows через командную строку

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

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