DEV Community

Cover image for OAuth Login Authentication with identity provider in Xamarin.Forms
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

OAuth Login Authentication with identity provider in Xamarin.Forms

Many applications require the addition of user authentication, and this always means enabling your users to sign in to their existing Facebook, Yahoo, Google, and now Apple Pull sign-in accounts.

Image description

OAuth is an authentication framework that allows the application to obtain limited access to HTTP service users' accounts on Facebook, Yahoo, Google, Microsoft, etc. Nowadays, there is no need to make registration logic. Alternatively, you can select the identity provider using the login. In this case, an individual sign up for the application using the identity provider's login, an account is created for them, and the authentication step is taken by the identity provider.

In this article, we will understand how to implement the following OAuth identity provider in Xamarin Forms and how to manage the authentication process in Xamarin.Forms application.

  1. Google
  2. Facebook
  3. Twitter
  4. Microsoft
  5. Linkedin

Image description

Now let's go step by step how to create an OAuth Login form in Xamarin Android.

We are creating this project in Visual Studio 2019, so you too should try to use the latest versions.

Step 1 - Create New Xamarin.Forms Project

Open Visual Studio -> Create New Project -> Mobile App (Xamarin.form)

Then click on the Next button. Note the highlight point of the image as shown in the image. We are developing mobile phones so mobile phones have to be selected.

Image description

Step 2: Give the project name

You can give your project the name you want. Enter the name of your project and click on the create button our project name is OAuthLoginAuthentication which you can see in the image.

Image description

Step 3: Select template

From this, you can select whatever you want. All are templates, we only need a blank page then select the last option which will be a blank page.

If you need a Flyout layout you can also select the first option flyout drawer which will provide you a Flyout.

Read More: Page Navigation Between Two Pages In Xamarin.forms

If you need a tab menu, you can also select the second option Tabbed App which will provide you a tab menu.Then click on Create

Image description

Now our project is set up as a normal model. And, we will add a component, API class, layout, NuGet package, required class, and interface.

Step 4 - Install OAuth Client Components

Xamarin.Auth is an all-platform SDK to authenticate users and store their accounts. It has authenticators that provide support for the use of identity providers.

Let's add Xamarin.Auth component to OAuth. We have to add this separately to all platform-specific projects.

Go to Solution Explorer (Right -side) -> OAuthLoginAuthentication.Droid-> Components -> Right-click on select "Get More Components".

If you are not already logged in, the login page will be displayed. Then connect to it. Next, search for the Xamarin.Auth component and double-click and click "Add to App"

Step 5 - Create Base Login Page (SecuredLoginPage.Xaml)

We have created quick and easy login screens. You can change them as per your needs.

Go to Solution Explorer (Right -side)->Right-click on Portable Class Library - Add New Item - Select Xaml Page (SecuredLoginPage).


  <contentpage x:class="OAuthLoginAuthentication.SecuredLoginPage" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:local="clr-namespace:OAuthLoginAuthentication" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">  
    <stacklayout>  
        <entry placeholder="Emaild">  
        <entry ispassword="true" placeholder="Password"><button height="80" text="Login"></button><button clicked="LoginClick" height="30" image="googlelogo.png" text="Google"></button><button clicked="LoginClick" height="30" image="facebooklogo.png" text="Facebook"></button><button clicked="LoginClick" height="30" image="teitterlogo.png" text="Twitter"></button><button clicked="LoginClick" height="30" image="gitlogo.png" text="GitHub"></button><button clicked="LoginClick" height="30" image="yahoologo.png" text="Yahoo"></button><button clicked="LoginClick" height="30" image="dropboxlogo.png" text="Drop-box"></button><button clicked="LoginClick" height="30" image="linkedinlogo.png" text="Linked-In"></button><button clicked="LoginClick" height="30" image="flickerlogo.png" text="Flicker"></button><button clicked="LoginClick" height="30" image="microsoftlogo.png" text="Twitter"></button></entry></entry></stacklayout></contentpage>

Enter fullscreen mode Exit fullscreen mode

SecuredLoginPage.Xaml.cs

Add SecuredLoginPage event in SecuredLoginPage page code behind the file and the sender object will return the button text name (eg: Twitter, Yahoo, etc).


using System;
using Xamarin.Forms;  
namespace OAuthLoginAuthentication {  
    public partial class SecuredLoginPage: ContentPage {  
        public SecuredLoginPage() {  
            InitializeComponent();  
        }  
        void LoginClick(object sender, EventArgs args) {  
            Button btncontrol = (Button) sender;  
            string providername = btncontrol.Text;  
            if (OAuthConfig.User == null) {  
                Navigation.PushModalAsync(new ProviderLoginPage(providername));  

            }  
        }  
    }  
}

Enter fullscreen mode Exit fullscreen mode

Step 6 - Create identity provider login page

As we will be implementing Xamarin.Auth platform-specific login page, we do not need any specific implementation in a portable project. We do not need to simply add the provider login page which will be resolved at runtime and will be replaced by actual implementation in this regard, which will be explained in step 7.

Right Click Portable Project -> Add New Item ->Select Xaml page (ProviderLoginPage.Xaml).


using System;
using Xamarin.Forms;  
namespace OAuthLoginAuthentication {  
    public partial class SecuredLoginPage: ContentPage {  
        public SecuredLoginPage() {  
            InitializeComponent();  
        }  
        void LoginClick(object sender, EventArgs args) {  
            Button btncontrol = (Button) sender;  
            string providername = btncontrol.Text;  
            if (OAuthConfig.User == null) {  
                Navigation.PushModalAsync(new ProviderLoginPage(providername));  

            }  
        }  
    }  
}

Enter fullscreen mode Exit fullscreen mode

Step 7: Create Platform Specific Login Renderer

We need to create a platform-specific LoginRenderer Page. Thus, you need to create a specific login page (loginRenderer. CS) for iOS, Android, and UWP projects.

We need to add a Login page render that will be used by Xamarin.Auth to display the web view for the OAuth log-in page.

Code Snippet Explanation
The following code is for Xamarin.Forms Dependency service that maps the provider login page to a login renders.


using System;
using Xamarin.Forms;  
namespace OAuthLoginAuthentication {  
    public partial class SecuredLoginPage: ContentPage {  
        public SecuredLoginPage() {  
            InitializeComponent();  
        }  
        void LoginClick(object sender, EventArgs args) {  
            Button btncontrol = (Button) sender;  
            string providername = btncontrol.Text;  
            if (OAuthConfig.User == null) {  
                Navigation.PushModalAsync(new ProviderLoginPage(providername));  

            }  
        }  
    }  
}

Enter fullscreen mode Exit fullscreen mode

Create an OAuthProviderSetting class from a portable class library by implementing OAuth. That is explained in step 8.


OAuthProviderSetting oauth = new OAuthProviderSetting();  
var auth = oauth.LoginWithProvider(providername);  
Create Oauth event  
for provider login completed and canceled.  
auth.Completed += (sender, eventArgs) => {  
        if (eventArgs.IsAuthenticated) { //Login Success }  
            else {  
                // The user canceled 
            }  
        };

Enter fullscreen mode Exit fullscreen mode

If you want to retrieve and save user information. You can create a username from a portable library and refer to the code below.


namespace DevEnvExeLogin {  
    public class UserDetails {  
        public string TwitterId {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string ScreensName {  
            get;  
            set;  
        }  
        public string Token {  
            get;  
            set;  
        }  
        public string TokenSecret {  
            get;  
            set;  
        }  
        public bool IsAuthenticated {  
            get {  
                return !string.IsNullOrWhiteSpace(Token);  
            }  
        }  
    }  
} 

Enter fullscreen mode Exit fullscreen mode

Planning to Hire Xamarin App Development Company? Your Search ends here.

LoginsRenderer.CS


[assembly: ExportRenderer(typeof(ProviderLoginPage), typeof(LoginsRenderer))]  
namespace DevEnvExeLogin.Droid.PageRender {  
  public class LoginRenderer: PageRenderer {  
    bool showLogin = true;  
    protected override void OnElementChangeds(ElementChangedEventArgs < Page > e) {  
      base.OnElementChanged(e);  

      var loginPage = Element as ProviderLoginPage;  
      string providername = loginPage.ProviderName;  
      var activity = this.Context as Activity;  
      if (showLogin && OAuthConfig.User == null) {  
        showLogin = false;  

        OAuthProviderSetting oauth = new OAuthProviderSetting();  
        var auth = oauth.LoginWithProvider(providername);  

        auth.Completed += (sender, eventArgs) => {  
          if (eventArgs.IsAuthenticated) {  
            OAuthConfig.User = new UserDetails();  
                       // Get and Save User Details   
                       OAuthConfig.User.Token = eventArgs.Account.Properties["oauth_token"];  
                       OAuthConfig.User.TokenSecret = 
eventArgs.Account.Properties["oauth_token_secret"];  
                        OAuthConfig.User.TwitterId = eventArgs.Account.Properties["user_id"];  
                        OAuthConfig.User.ScreenName = eventArgs.Account.Properties["screen_name"];  
                        OAuthConfig.SuccessfulLoginAction.Invoke();  
                    } else {  
                        // The user cancelled  
                    }  
                };  
                activity.StartActivity(auth.GetUI(activity));  
            }  
        }  
    }  
} 

Enter fullscreen mode Exit fullscreen mode

Step 8: OAuth Implementation

The OAuth2Authenticator class is responsible for managing the user interface and interacting with authentication services. It will support all identity providers.

The OAuth2Authenticator and OAuth1Authenticator classes require some parameters, as shown in the list below.

Client ID- Identity provider-client ID. When registering the application, you will require a single client ID.

Secret Client – Identifies the client applying. When registering the application, you will need a unique customer privilege.

Scope – Identifies access to the API requested by the application, and the value informs the consent screen which is displayed to the user.

Authorize URL – Indicates the URL from which the permission code will be obtained.

Redirection URL – Identifies the URL from which the reply will be sent. The value of this parameter should correspond to one of the values displayed on the Project Identifiers page.

Access Token URL — Identifies the URL used to ask for access tokens after obtaining an authorization code.

Step 9: Google Account Login Data


var googleauth = new OAuth2Authenticator (  
"ClientId",  
"ClientSecret",  
"https://www.googleapis.com/auth/userinfo.email",  
new Uri("https://accounts.google.com/o/oauth2/auth"),  
new Uri ("http://www.myside.com"),new Uri("https://accounts.google.com/o/oauth2/token")  
); 

Enter fullscreen mode Exit fullscreen mode

Note: We have just written the code about the google account here. If you need another account, you can follow the link below.

https://www.c-sharpcorner.com/article/oauth-login-authenticating-with-identity-provider-in-xamarin-forms/

You can also download source code from the other site.

Conclusion

In this blog, we have seen the normal code but you can also do it in MVVM depending on your project requirements. The samples shown here are the basis to implement authentication in your Xamarin Forms application. As we discussed in the blog, you can log in with any site for which you need Client ID or AppID and Client secret.

Top comments (1)

Collapse
 
vdelitz profile image
vdelitz

Hey man, great article about adding Oauth logins tin Xamarin.Forms - recently I dug deeper into WebAuthn / passkeys as authentication, any experience here as well?