Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Xamarin.Forms with Xamarin.Auth to store and retrieve Account object

In a Xamarin.Forms project and I'd like to use Xamarin.Auth just to store and retrieve Account object securely. Please note that I am not taking about integrating with Facebook, Google or any other service that serves end-to-end oAuth login experience.

like image 241
Karthik Murugesan Avatar asked Feb 03 '26 15:02

Karthik Murugesan


2 Answers

If you are only after secure storage of objects then XLabs.Platform has ISecureStorage interface which is implemented for iOS, Android & WP. If you are working with Forms I would suggest installing XLabs.Forms package from NuGet and then using Ioc (XLabs.Ioc) inject the implementations to PCL code. You can also use XLabs.Serialization to serializer/deserialize bytes using Json.NET, ServiceStack or other serializers like ProtoBuffer (available as XLabs.Serialization plugins).

https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/src/Platform/XLabs.Platform/Services/ISecureStorage.cs

https://www.nuget.org/packages?q=XLabs

like image 63
SKall Avatar answered Feb 06 '26 05:02

SKall


This topic is being discussed over at the Xamarin Forums. You might want to check out the thread there.

Xamarin.Auth is not a PCL and platform specific. You'll need to work with custom renderers. First create a Forms page for your login:

public class LoginPage : ContentPage
{
}

then implement it for the platforms, here for instance iOS:

[assembly: ExportRenderer (typeof (LoginPage), typeof (LoginPageRenderer))]

namespace Demo.XForms.iOS
{
    public class LoginPageRenderer : PageRenderer
    {
        public override void ViewDidAppear (bool animated)
        {
            base.ViewDidAppear (animated);

            var auth = new OAuth2Authenticator (
                clientId: ...,
                scope: "basic",
                authorizeUrl: new Uri ("..."),
                redirectUrl: new Uri ("..."));

            auth.Completed += (sender, eventArgs) => {
                DismissViewController (true, null);
                if (eventArgs.IsAuthenticated) {
                    App.SaveToken(eventArgs.Account.Properties["access_token"]);
                } else {
                    // The user cancelled
                }
            };

            PresentViewController (auth.GetUI (), true, null);
        }
    }
}

With that in place you can use it from within Forms:

this.MainPage = new LoginPage ();
like image 37
Krumelur Avatar answered Feb 06 '26 04:02

Krumelur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!