{"id":16687161,"url":"https://github.com/redth/xamarin.aspnetcore.authentication","last_synced_at":"2025-04-10T00:20:23.639Z","repository":{"id":137487560,"uuid":"225430628","full_name":"Redth/Xamarin.AspNetCore.Authentication","owner":"Redth","description":"Add authentication to your Xamarin apps using Asp.Net Core's built in authentication and providers","archived":false,"fork":false,"pushed_at":"2020-01-13T21:01:56.000Z","size":648,"stargazers_count":15,"open_issues_count":1,"forks_count":1,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-01T22:41:48.156Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Redth.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-12-02T17:24:06.000Z","updated_at":"2023-04-04T21:34:05.000Z","dependencies_parsed_at":null,"dependency_job_id":"d66abbb2-8c37-444d-b976-20c49562bc74","html_url":"https://github.com/Redth/Xamarin.AspNetCore.Authentication","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Redth%2FXamarin.AspNetCore.Authentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Redth%2FXamarin.AspNetCore.Authentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Redth%2FXamarin.AspNetCore.Authentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Redth%2FXamarin.AspNetCore.Authentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Redth","download_url":"https://codeload.github.com/Redth/Xamarin.AspNetCore.Authentication/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248131846,"owners_count":21052936,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-12T15:08:03.144Z","updated_at":"2025-04-10T00:20:23.623Z","avatar_url":"https://github.com/Redth.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Xamarin.AspNetCore.Authentication\nSample for how to use AspNetCore Authentication providers with Xamarin mobile apps\n\n\n## The Challenge\n\nAdding authentication providers to your Xamarin Mobile apps can be challenging.  There are many different approaches, some of which are no longer considered appropriate due to security concerns (you should never embed a client secret in your Mobile app), and some of which require native SDK's with no common set of API's to implement from a Xamarin cross platform app.\n\nThe goal is to provide a cross platform API to authenticate with a variety of providers in a Xamarin mobile app, with minimal dependencies in a secure implementation.\n\n## The Solution\n\nASP.NET Core provides an easy to setup and use implementation of OAuth and OpenID Connect authentication with a variety of providers supported by Microsoft, and even more supported by the ASP.NET Contrib repository.  Leveraging this work makes sense from an engineering and support efficiency perspective, as well as from a security perspective.\n\nUsing ASP.NET Core's authentication model, the server backend can handle all of the authentication implementation, and the front end Xamarin mobile app only needs to know how to initiate the process and listen for a callback.\n\nThe flow using this solution looks something like this:\n\n![Flow](Assets/Xamarin.AspNetCore.Auth-Diagram.png)\n\n\nThe concept is to provide two NuGet packages:\n - Xamarin.AspNetCore.Auth - containing the ASP.NET Middleware to help with the mobile authentication flow initiation and app URI redirect callback logic\n - Xamarin.AspNetCore.Auth.Mobile - the client side Xamarin App implementation of calling out to the platform specific browser controls and waiting for and parsing the callback from the backend\n\n\n## Using the NuGet's in your Backend and Xamarin App\n\n### ASP.NET Backend Configuration\n\nYou would install the `Xamarin.AspNetCore.Auth` NuGet package in your ASP.NET Core backend project.\n\nIn your `ConfigureServices` method in the `Startup.cs` file, you need to call `UseXamarinAuth` before you call `AddAuthentication`:\n\n```csharp\nservices.AddXamarinAuth(o =\u003e\n    {\n        o.CallbackUri = new Uri(\"myapp://\");\n    });\n```\n\nNotice that you must specify your app's callback URI Schema in the configuration options so the middleware knows where to redirect to.\n\nAfter this code you can call `AddAuthentication` as you normally would in your app, adding any providers you wish to use.  For example:\n\n```csharp\nservices.AddAuthentication()\n    .AddCookie()\n    .AddFacebook(fb =\u003e\n    {\n        fb.AppId = \"123456789\";\n        fb.AppSecret = \"xxxxxxxxxxx\";\n        fb.SaveTokens = true;\n    });\n```\n\n\u003e IMPORTANT: Notice the `SaveTokens = true` which is required to be set for any providers you wish to use with the Xamarin app and the Xamarin middleware.\n\nIn your `Startup.cs`'s `Configure` method, you need to call `app.UseXamarinAuth();` before `app.UseRouting()` and before `app.UseAuthentication()`.\n\n\n### Xamarin App Configuration\n\nAfter installing the `Xamarin.AspNetCore.Auth.Mobile` NuGet package, you will need to setup your platform specific initializations:\n\n#### iOS\n\nIn your `AppDelegate.cs` you should add the following method:\n\n```csharp\npublic override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)\n{\n    if (Xamarin.AspNetCore.Auth.Mobile.Platform.OpenUrl(app, url, options))\n        return true;\n\n    return base.OpenUrl(app, url, options);\n}\n```\n\nYou will also need to ensure your `Info.plist` contains a registration of your app's callback schema.  For `myapp://` it would look like:\n\n```xml\n\u003ckey\u003eCFBundleURLTypes\u003c/key\u003e\n\u003carray\u003e\n    \u003cdict\u003e\n        \u003ckey\u003eCFBundleURLSchemes\u003c/key\u003e\n        \u003carray\u003e\n            \u003cstring\u003emyapp\u003c/string\u003e\n        \u003c/array\u003e\n    \u003c/dict\u003e\n\u003c/array\u003e\n```\n\n#### Android\n\nIn your `MainActivity`'s `OnCreate`  you need to initialize the library with this call:\n\n```csharp\nXamarin.AspNetCore.Auth.Mobile.Platform.Init(this.Application);\n```\n\nYou will also need to add a call to your `MainActivity`'s `OnResume` like this:\n\n```csharp\nprotected override void OnResume()\n{\n    base.OnResume();\n\n    Xamarin.AspNetCore.Auth.Mobile.Platform.OnResume(Intent);\n}\n```\n\nFinally, you need to subclass `AuthCallbackActivity` with the appropriate attributes (notice the `DataScheme` value of `myapp` here to handle `myapp://` schema callbacks):\n\n```csharp\n[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop)]\n[IntentFilter(new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, \n    DataScheme = \"myapp\")]\npublic class AuthCallbackActivity : Xamarin.AspNetCore.Auth.Mobile.AuthCallbackActivity\n{\n}\n```\n\n\n### Authenticating from your Xamarin App\n\nWith everything configured you need to only know a few key pieces of information to begin authenticating from your Xamarin App's shared code:\n\n - ASP.NET Backend Base URL (eg: `https://myapp.com/`)\n - Your App's Redirect Scheme (eg: `myapp://`)\n - The Provider name you wish to authenticate with\n\nHere is an example of authenticating with this information:\n\n```csharp\nvar r = await Authentication.AuthenticateAsync(new Uri(\"myapp://\"), new Uri(\"https://myapp.com\"), \"GitHub\");\n```\n\nThe provider name correlates to the authentication scheme name for the providers you added.  The default is typically obvious (eg: `\"GitHub\"`, or `\"Facebook\"`, or `\"Google\"`) but if you change the name in your options you will have to use the correct name here.\n\n\n### Customization\n\nThere are some assumed conventions with the configuration above.  First of all, this assumes you are ok with the Xamarin middleware capturing the default route of `/mobileauth` on your backend project.  You can change this by setting the `AuthPath` in the `XamarinAuthOptions` when calling `services.UseXamarinAuth(o =\u003e o.AuthPath = \"/custompath\");`.  You would also need change your Xamarin App's `AuthenticateAsync` call to specify the `authenticationPath: \"/custompath\"` parameter to match.\n\nBy default the app callback will include a URI fragment containing tokens and expiration epoch time (if available) like the following:\n\n```\n#access_token=xyz\u0026refresh_token=zyx\u0026expires_in=3600\n```\n\nIf you want to send something different back to the app (for instance, you might want to generate your own JWT on the backend from the access token and send that back to the client instead), you can set the `AuthenticatedRedirectHandler` delegate on the `XamarinAuthOptions` when configuring your services:\n\n```csharp\nservices.UseXamarinAuth(o =\u003e {\n    o.AuthenticatedRedirectHandler = (HttpContext httpContext, AuthenticateResult authResult, IDictionary\u003cstring, string\u003e callbackParams) =\u003e {\n\n        var customAccessToken = GenerateCustomAccessToken(callbackParams);\n\n        // Don't send back any of the provider's tokens or expiration\n        callbackParams.Clear();\n\n        // Add our custom token to the parameters to callback with to the app\n        callbackParams.Add(\"access_token\", customAccessToken);\n        callbackParams.Add(\"expires_in\", DateTime.UtcNow.AddDays(1).ToUnixTimeSeconds());\n    };\n});\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredth%2Fxamarin.aspnetcore.authentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fredth%2Fxamarin.aspnetcore.authentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredth%2Fxamarin.aspnetcore.authentication/lists"}