Code Monkey home page Code Monkey logo

mobileauth-lib's Introduction

MobileAuth Library

The MobileAuth Library is a helper library to help produce an OAuth endpoint using AspNetCore Minimal APIs for your Mobile Application. This can be done in just a few lines of code. Out of the box using the library you can support Sign In with Apple, Google, and Microsoft Accounts. These require no manual configuration in code and only for the configuration values to be added to the host or appsettings.json file. Additional / Custom providers can easily be added as well.

var builder = WebApplication.CreateBuilder(args);

builder.AddMobileAuth();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

// maps https://{host}/mobileauth/{Apple|Google|Microsoft}
app.MapMobileAuthRoute();

app.Run();

Configuration

The only required part of the configuration is the CallbackScheme. This can be anything you want and will be used in the redirect url. Note the redirect url will be formatted as {CallbackScheme}://auth?access_token={jwt}&expires_in={expires timestamp in Unix Seconds}. This is meant to be used with the Xamarin or Maui Essentials WebAuthenticator.

{
  "OAuth": {
    "CallbackScheme": "yourappscheme",
    "JwtKey": "yoursecretkey",
    "Apple": {
      "ServiceId": "{Apple Service Id}",
      "TeamId": "{Your Apple Team Id}",
      "KeyId": "{Your Apple Key Id}",
    },
    "Google": {
      "ClientId": "{Google Client Id}",
      "ClientSecret": "{Your Google Client Secret}",
    },
    "Microsoft": {
      "ClientId": "{Microsoft Client Id}",
      "ClientSecret": "{Your Microsoft Client Secret}",
    }
  }
}

Jwt

In order to better assist you in providing authentication with your API the library will automatically wrap any claims into a self signed JWT. By default if no key is provided it will use a development key. You should be sure to update this for production scenarios. After your user has been authenticated you can use the AccessToken to authenticate with your API. Within this JWT you may find an original access token from the OAuth provider. If you need to access any API from Google or Microsoft for example you can use the original access token to authenticate with the API.

Apple Configuration

As with any app you will need to set up a new App Id in the Apple Developer Portal. Before you get very far you can grab the Team Id out of the Developer Portal. Just beneath your name in the Developer Portal you should see the Company Name / Team Name along with the Team Id My Company - VK8ZR2JK2E. You'll use the VK8ZR2JK2E as the Team Id in your configuration.

If you have not already created an App Id, you should start there. For this example we'll say the App Id is com.example.myapp. Be sure to enable the Sign In with Apple capability.

Once you've done this you should create a Key. Select the Keys option and then create a new Key. You can give it a name like MyAppSIWA, be sure to select the Sign in with Apple option. You'll need to click the configure button and select the Primary App Id that you created in the previous step, and hit save.

NOTE: When selecting the primary app id, it will show up like My Awesome App (DKD783KDELD.com.example.myapp), where DKD783KDELD is the App Id. It will then show below a Grouped App Id like DKD783KDELD.com.example.myapp.sid.

Once you have the Key, it should have downloaded with a file name like AuthKey_IUK783KD3R9.p8, where IUK783KD3R9 is the Key Id that you will need for your configuration.

When you're done you'll want to go back to the Identifiers and toggle from App IDs to Service IDs. You will need to create a the Service Id for your App as com.example.myapp.sid which you saw in the Grouped App Id, you will naturally provide this as the Service Id in your configuration. Again enable the Sign In with Apple capability, and this time when you configure it, it will prompt you for a host name and callback. Apple will NOT allow you to use localhost as an authorized host. You must deploy this or update your hosts file have something like myapp.com mapped back to 127.0.0.1. You can then use myapp.com as an authorized host where the callback is https://myapp.com/signin-apple.

NOTE: Be sure the generated key is in the App_Data directory with the name AuthKey_{Your KeyId}.p8.

To provide additional flexibility you can provide values for the following optional configuration values:

{
  "OAuth": {
    "Apple": {
      "PrivateKey": "{The text value for your private key}", // Recommended for development only
      "UseAzureKeyVault": true // Optional, defaults to false
    }
  }
}

When using Azure Key Vault we will only update the Apple Registration to ensure that your p8 is loaded from the Azure Key Vault however you will still need to properly configure your application to connect to the Azure Key Vault.

Google / Microsoft Configuration

Microsoft actually has decent docs on this please see:

Again once you've got your Client Id & Client Secret you simply need to provide them in your configuration when using this library.

Additional Providers

You can opt out of using any built in providers by simply not providing the required configuration values. In order to add additional providers you can access the AuthenticationBuilder and register any other providers you may need when calling the AddMobileAuth method.

builder.AddMobileAuth(auth => {
    auth.AddFacebook(o => {
        o.ClientId = "{Facebook Client Id}";
        o.ClientSecret = "{Facebook Client Secret}";
    });
    // etc...
});

Customize Returned Claims

By Default the library will attempt to return the following claims:

  • The User's Given Name, Surname, & Full Name
  • The User's Email Address
  • The Authentication Provider (Apple, Google, Microsoft)
  • The Authentication Provider's User/Object Id
  • The Access & Refresh Tokens
  • When the Token Expires as a UTC time in Unix Seconds

Whether you need to inject some additional logic or if you just want to customize how the claims are returned, it is very easy to do. You simply need to implement IMobileAuthClaimsHandler and register it with the MobileAuthenticationBuilder like so:

builder.AddMobileAuth(auth => {
    auth.AddMobileAuthClaimsHandler<MyCustomMobileAuthClaimsHandler>();
});

Run The Sample

Each of the supported providers has a default callback signin-{provider}. For example, when configuring the domain & callback in the Google console for local testing with the demo app you would use https://localhost:7172/signin-google. Similarly you would use the localhost domain for Microsoft. However it is important to note that Apple does NOT support localhost. In the case of Apple, for local testing you will need to use a normal formatted (does not need to be real) domain. You can then update the hosts file on your local machine to map the domain to the localhost IP address.

mobileauth-lib's People

Contributors

dansiegel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

mobileauth-lib's Issues

Wrong URL in DemoApp

Struggled for over an hour until I realized the URL for the WebAuthenticator is wrong.

In the code it is:
Url = new Uri(new Uri(Constants.BaseUrl), $"mobileauth/{scheme}")

And it should be:
Url = new Uri(new Uri(Constants.BaseUrl), $"mobileauth/signin{scheme}")

Tutorial Request: Authentication & Authorization for Blazor Maui

Note, my goal is to convert my Blazor app over to Maui without using actual Maui forms. But I understand we have to use the Maui forms for authentication. It would be awesome if you did a video on that scenario. My solution:

  • Backend:
    • ASP.NET Core API
  • Front-ends:
    • Blazor Server
    • MAUI
    • Blazor WASM
  • Shared:
    • API Helper (DTOs and any authentication/authorization code shared between API and all front-ends)
    • UI (All the business forms and logic. Shared between all front-ends)

The Shared.UI contains all the Blazor forms from a past project. The API needs to know the Username/Id of the logged in user to obtain permissions from the solutions MS SQL server.

Thanks for the considerations!

Sample is simply not working

I've configured for google oAuth, added my client id and secret.
Allowed localhost:7127 as well as https://localhost:7172/signin-google and https://localhost:7172/mobileauth/google on Authorized redirect URIs
Simply not working.

Google: If app runs on multiple platforms, each will need its own client ID.

Hello! How may I specify different Google CliendId, if my application runs on several platforms? From Google Cloud -> Create OAuth client ID:
A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms, each will need its own client ID. See [Setting up OAuth 2.0 ](https://developers.google.com/identity/protocols/oauth2/) for more information. [Learn more ](https://support.google.com/cloud/answer/6158849) about OAuth client types.

Samples dont work

All kinds of problem...first being the mobile app uses path /mobileauth/apple and the server is publishing /mobileauth/signin{scheme}. I am using NGROK to redirect and still does not work.

Sign in button not firing a click event

Hi,
Just downloaded and ran, when debugging with Win, the clicking of the sign in buttons didn't result in anything happening. The image was not in a position like in your video, it was spaced over top of the buttons, so I hide the image and tried again. Still the clicking of the buttons didn't result in anything or run any code on click as far as I can tell.

Thanks

Signout throws exception when called

When i call signout endpoint, and i logged via google, i received exception:

System.InvalidOperationException: The authentication handler registered for scheme 'Google' is 'GoogleHandler' which cannot be used for SignOutAsync. The registered sign-out schemes are: Cookies.

I don't know, is miss configuration for my side?

DemoMobileApp.build.appxrecipe does not exist

Just downloaded and ran the sample by setting the API and MobileApp to start on debug. Ran debug with no changes and received the following error. (BTW, in your excellent video you mention a patch update coming but the version number on NuGet today is the same as in the video, thanks). Note, I didn't create a GitHub repository, I just downloaded the code and ran in debug. Is there an additional step I need to setup a repository?

DEP1700: The recipe file "D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp\bin\Debug\net6.0-android\DemoMobileApp.build.appxrecipe" does not exist. You may need to build your project.
2>Deployment of the application to the target device failed.
========== Build: 1 succeeded, 0 failed, 2 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========

I did a solution clean all, then a solution rebuild and received these errors:

Rebuild started...
Restored D:\MyCompany\VS Projects\mobileauth-lib-master\src\AvantiPoint.MobileAuth\AvantiPoint.MobileAuth.csproj (in 22 ms).
Restored D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoAPI\DemoAPI.csproj (in 22 ms).
Restored D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp\DemoMobileApp.csproj (in 493 ms).
1>------ Rebuild All started: Project: DemoMobileApp, Configuration: Debug Any CPU ------
2>------ Rebuild All started: Project: AvantiPoint.MobileAuth, Configuration: Debug Any CPU ------
2>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(25,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\src\AvantiPoint.MobileAuth'.
2>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(48,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\src\AvantiPoint.MobileAuth'.
2>C:\Users\Brian\.nuget\packages\microsoft.sourcelink.common\1.1.1\build\Microsoft.SourceLink.Common.targets(53,5): warning : Source control information is not available - the generated source link is empty.
2>AvantiPoint.MobileAuth -> D:\MyCompany\VS Projects\mobileauth-lib-master\src\AvantiPoint.MobileAuth\bin\Debug\net6.0\AvantiPoint.MobileAuth.dll
2>Successfully created package 'D:\MyCompany\VS Projects\mobileauth-lib-master\Artifacts\AvantiPoint.MobileAuth.0.1.0-g.nupkg'.
2>Successfully created package 'D:\MyCompany\VS Projects\mobileauth-lib-master\Artifacts\AvantiPoint.MobileAuth.0.1.0-g.snupkg'.
2>Done building project "AvantiPoint.MobileAuth.csproj".
3>------ Rebuild All started: Project: DemoAPI, Configuration: Debug Any CPU ------
3>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(25,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoAPI'.
3>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(48,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoAPI'.
3>C:\Users\Brian\.nuget\packages\microsoft.sourcelink.common\1.1.1\build\Microsoft.SourceLink.Common.targets(53,5): warning : Source control information is not available - the generated source link is empty.
3>DemoAPI -> D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoAPI\bin\Debug\net6.0\DemoAPI.dll
3>Done building project "DemoAPI.csproj".
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(25,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(48,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.sourcelink.common\1.1.1\build\Microsoft.SourceLink.Common.targets(53,5): warning : Source control information is not available - the generated source link is empty.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(25,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(48,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.sourcelink.common\1.1.1\build\Microsoft.SourceLink.Common.targets(53,5): warning : Source control information is not available - the generated source link is empty.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(25,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(48,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.sourcelink.common\1.1.1\build\Microsoft.SourceLink.Common.targets(53,5): warning : Source control information is not available - the generated source link is empty.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(25,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.build.tasks.git\1.1.1\build\Microsoft.Build.Tasks.Git.targets(48,5): warning : Unable to locate repository with working directory that contains directory 'D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp'.
1>C:\Users\Brian\.nuget\packages\microsoft.sourcelink.common\1.1.1\build\Microsoft.SourceLink.Common.targets(53,5): warning : Source control information is not available - the generated source link is empty.
1>DemoMobileApp -> D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp\bin\Debug\net6.0-ios\iossimulator-x64\DemoMobileApp.dll
1>DemoMobileApp -> D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp\bin\Debug\net6.0-android\DemoMobileApp.dll
1>DemoMobileApp -> D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp\bin\Debug\net6.0-maccatalyst\maccatalyst-x64\DemoMobileApp.dll
1>DemoMobileApp -> D:\MyCompany\VS Projects\mobileauth-lib-master\sample\DemoMobileApp\bin\Debug\net6.0-windows10.0.19041.0\win10-x64\DemoMobileApp.dll
1>Done building project "DemoMobileApp.csproj".
========== Rebuild All: 3 succeeded, 0 failed, 0 skipped ==========

The oauth state was missing or invalid.

When trying your sample code, I'm running into a issue

I've deployed the server code and only changed the clientid,secret settings for the google login
When testing the login, I can see the google consent screen.

When selecting an already active session, I'm redirected back to the localhost:1792 but get the following error

System.Exception: The oauth state was missing or invalid.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.