Hello friends, here is my second post about social auth with Xamarin Forms and ASP.net core. The previous method, though functional is kind of old and less recommended than this new approach. A few months ago, a new feature was added to Xamarin Essentials, permitting us to easily implement authentication with a back-end API (not only ASP.net core). This feature is better than previous authentication mechanisms, primarily because it avoids us from adding our application credentials inside our mobile app’s source code. And also, it is very easy to implement. Together, we will not only go through the process of implementing JWT social auth with ASP.net core and Xamarin Essentials, but we will also highlight and solve some difficulties you might face when implementing this feature in a real-world application. So, lets dive in.

Xamarin Essentials is constantly improving, and one of the features which were added a few months ago is the Web Authenticator API. This feature provides an abstraction layer over the process of integrating authentication, calling the web browser, Managing redirects e.t.c in our Xamarin App.

HERE is the source code for this post.

What we will do

  • Setup Social authentication with the Back-end and mobile app
  • Getting user information from social media
  • Adding Aspnetcore identity and Generating our own JWT tokens

This post is associated to the video on my channel.

JWT Social Auth with Asp.net Core and Xamarin Essentials

Let’s setup our apps on social media

  • First, we have to setup our client app on social media, in our case we use Google and Facebook.
  • Then we get our app secrets and ids. This process is simple, and well documented so, I just highlighted how to setup your redirect URLs properly in the video associated to this post.
  • Then we create an ASP net core project and setup Cookie and JWT authentication. Adding Google and Facebook auth with the Credentials we saved earlier

Note: If you are using both Cookie and JWT auth scheme in your API, you can chose which scheme to use in your controllers using this attribute.

Social Authentication Process

The mobile authentication process is simple and will take place as follows:

  • Xamarin Essentials calls our API passing the scheme (Facebook or Google in our case) depending on which social media the user wants to authenticate to.
  • Our backend checks if the user is authenticated
  • If he is not, we start a challenge, redirecting the user to the social media’s authentication page. Xamarin Essentials handles this redirection on the client side for us.

Note: Once the challenge succeeds we are returned an access token. This token is not used to authenticate to our API. It is from the social media and we will use it later to get more user information.

  • Then, once the user authenticates, we get his information using appropriate claims.
  • We then URL encode this user information and redirect. Xamarin Essentials will get the redirect URL and decode it to use in our app.

Note that, the call back scheme above represents a scheme we will define in our mobile app we will name it: “xamarinapp”

Getting the User’s Picture

You might have noticed that the user’s picture is not passed to our backend even after authentication. We can get this with the access token returned from the social media, which we mentioned earlier, or add appropriate claims when setting up authentication.

  • For Google, we will just add a little bit of configuration while setting up the Authentication in our startup.cs
  • For Facebook, we will use the access token to request the user’s profil picture. Here is how we do that.

Adding JWT Auth

Now that we have our backend setup with social authentication, we need to handle the creation of tokens and managing users with ASPnet core identity. This is done easily. We will use mongodb as our database. But you could use sql server. The process is basically the same.

For this, we use this nugget package: AspNetCore.Identity.Mongo

  • Then, we configure Aspnet core identity as follows:
  • When a user authenticates, we want to create the user in our database or get this user if he already exists. Here is how we do it.
  • When the user completes social authentication, we then create a JWT token for this user, with appropriate claims. This token will be used for authentication. Here is how we do it.

Setting up Social Auth in the Mobile app

To setup JWT social auth with asp.net core and xamarin Essentials, we will have to create a Xamarin Forms project and add Xamarin Essentials. Then follow these steps.

  • We configure the callback scheme on iOS in the infor.plist file :
JWT social auth with asp.net core and xamarin Essentials URL Scheme iOS
JWT social auth with asp.net core and xamarin Essentials.URL Scheme iOS
  • Then on Android we create a web authenticator activity with an Action View intent.
  • We add a data scheme to this activity. This activity will be used during the authentication process by Xamarin Essentials.

Note: The callback scheme should be the same as that on the backend. The value you chose for its name is case sensitive, as mentioned in the documentation.

Now that we have configured the platform projects, let’s get into the shared project. Here, we will invoke the web authenticator API, and let it do the job of handling redirects, calling web browser e.t.c.

  • First, in our view model, we have two commands. One for each button, Signin with Facebook and Google.
  • Next, when we need to authenticate to our backend, we just call the web authenticator API, passing in the authentication URL and the callback scheme. Then that’s all.
  • When authentication succeeds, we can get the user’s information in the result returned.
  • Then using Shell navigation, we URL encode the user info and pass it to the User profile view model as follows.
  • If the user cancels the authentication process, or closes the browser before it completes, a “TaskCanceledException” will be thrown, and we need to handle it.

Conclusion

With just a few lines of code, we made JWT social auth with ASP.net core and Xamarin Essentials functionality in our mobile app. There Microsoft’s MSAL library for more advanced authentication scenarios. But for small size mobile applications, this approach is good enough. Especially if you are willing to prototype quickly.

References

https://devblogs.microsoft.com/xamarin/authentication-xamarin-essentials-aspnet/?WT.mc_id=DT-MVP-5003277

https://developer.android.com/reference/android/content/IntentFilter#addDataSchemeSpecificPart(java.lang.String,%20int)

Follow me on social media and stay updated

11 comments

  1. Andino Faturahman

    Reply

    Why i always get google auth token (auth.Properties.GetTokenValue(“access_token”)) on my mobile app ? even though I have replaced it with generated jwt token and even though I have remove auth.Properties.GetTokenValue(“access_token”) from code

    • Damien Doumer

      Reply

      I’m not sure I got you right, but what I can say is; You should generate the JWT code then pass that code down to the client, and please check the key value pair you return to your client after authentication calls.

  2. iknowshaun

    Reply

    Hi Doumer, great post. I’m just wondering how you went about testing it? I’ve managed to get everything in my Xamarin app working and on the asp.net core web api side. I can test the web api by sending a request and it works fine but when I send a request from my xamarin app to a web api running on my localhost it doesn’t return to the app, my guess is because it’s running on an emulator? Is there anything specific you have to setup for testing this on an emulator to your localhost web api?

    Regards
    Shaun

    • Damien Doumer

      Reply

      Hi, Thanks.
      Yeah, there is a way to test it from your emulator or any other external device.
      What I do is that I create a tunnel from my localhost to the internet, and make my local API available to any device which has an internet connection.

      To Create such tunnel, there are several solutuions out there, but the one I prefere, cause it is very easy to use is: Ngrock.
      To use it, just download the executable, and add the path to that executable in your OS’ environment variables.
      Then you can run this command : ngrok http https://localhost:44381/ -host-header="localhost:44381"
      replace the port with your app’s port, and a url will be given to you by ngrock, which you will use to hit your local dev env, and test your API safely.

      • iknowshaun

        Reply

        Thanks for the speedy reply. I’m actually using ngrok, and substituting the webauthenticator URL with that, so it hits my localhost through the tunnel but the problem occurs when Google does the callback to the server when authenticating. I’m guessing I have to add the ngrok tunnel in my Google oauth console too so it comes back on the same URL? (Instead of localhost)

        • Damien Doumer

          Reply

          Ooh, yeah I get it now. I had that issue too. I tried setting the redirect url to ngrok but the redirection won’t work that way with these social media platforms.
          When I implement this auth process, to debug, I deploy to a free tier in azure, and set the redirect url in the social media accounts, then from there I remote debug.
          Since this approach is not convenient for local testing, after debugging and ensuring that the auth process is ok, I add another simple auth mechanism for my local test scenarios “Only for test environment” such mechanism includes email and password signin and I return a JWT token to the client after the signin process.

          • iknowshaun

            I thought that might be the case. I’ll go down that route today. Thanks for all the advice dude.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.