Tutorial: Login with OAuth2.0

Serverless Authentication Login with OAuth2.0

Most end users already have accounts with major worldwide IT service providers such as Google or Facebook. Such providers provide with secure authentication APIs, generally based on the OAuth2.0 framework, aimed at third-party applications to safely identify end users. [[service]] SDK comes with APIs that make it easy to integrate authentication delegation to third-party OAuth2.0-compliant identity providers into your applications.

Currently supported providers are: Facebook, Google, GitHub, GitLab, Orange France and Mobile Connect for some Orange countries (Mobile Connect Orange thereafter). [[service]] can also automatically interact with any identity provider implementing OIDC (OpenID Connect), which is a simple identity layer on top of the OAuth 2.0 protocol.

By default all authentication delegation methods are disabled on new [[service]] applications. Developers have to explicitly enable them for each required provider using the "authentication" tab of the [[console]].

Note: Mobile Connect Orange consists in authenticating users using their mobile phone equipped with an Orange SIM card. On this purpose, final users (Orange customers) must have installed the Mobile Connect SIM application provided by Orange prior to use this authentication method, using the following links: Orange France customers, Orange Spain customers ("Mi Orange" tab, then "Entrar con Mobile Connect" section), Orange Jordan customers, Orange Morocco customers, Orange Madagascar customers.

OAuth2.0 Provider Applications

OAuth2.0 is actually an authorization framework rather than an authentication framework. Authorizations are granted by end users to entities generally known as applications, let call them here OAuth applications, as opposed to end-user applications developed using the [[service]] SDK. OAuth applications must be created by developers with the OAuth2.0 provider prior to invoking its authorization API. When an end-user application invokes the authorization method of the OAuth2.0 provider, the end user is first requested to log in and is then shown a consent screen to grant or deny authorizations required by the end-user application. The consent screen is filled with the information set up by the developer within the OAuth application (typically the application name, icon and description).

To create an OAuth application, OAuth2.0 providers generally provide with a developer console:

Once created, the authentication API of OAuth2.0 provider has to be subscribed for your OAuth application:

Provider How to subscribe the authentication API
Facebook Add the "Facebook Login" product (button "Add Product" at the bottom of the left panel).
Google In the "Identifiers" section, create a new "OAuth client ID" (dropdown button "Create Identifiers" at the top of the page), and select the "web application" type.
GitHub No explicit subscription neeeded.
GitLab No explicit subscription needed.
Orange France Subscribe to both "Authentication France" API and "User details France" API (button "Use this API" at the top of the page).
Mobile Connect Orange Subscribe to one or more of these APIs: Mobile Connect France - Limited, Mobile Connect Spain - Limited, Mobile Connect Jordan, Mobile Connect Madagascar - Limited, Mobile Connect Morocco (button "Use this API" at the top of the page).

Now you have to configure the OAuth2.0 redirect URI, that is, the URI where clients are redirected to when the authorization request completes [[snippet]]:

Provider How to set the redirect URI
Facebook Click on "Facebook Login" in the developer console of your OAuth application, and fill in the "Valid OAuth redirect URIs" field with:
[[baseUrl]]/auth/v2/<your-app>/facebook/callback
Google Click on the previously created "OAuth client ID", and fill in the "Authorized redirect URIs" field with:
[[baseUrl]]/auth/v2/<your-app>/google/callback
GitHub Click on the previously created OAuth application, and fill in the "Authorization callback URL" field with:
[[baseUrl]]/auth/v2/<your-app>/github/callback
GitLab When creating your OAuth application, fill the "Redirect URI" field with:
[[baseUrl]]/auth/v2/<your-app>/gitlab/callback
Orange France Click on the "Consent screen details" tab in the developer console of your OAuth application, and fill in the "Redirect URL" field with:
[[baseUrl]]/auth/v2/<your-app>/orange/callback
Mobile Connect Orange Click on the "Consent screen details" tab in the developer console of your OAuth application, and fill in the "Redirect URL" field with all of these values:
[[baseUrl]]/auth/v2/<your-app>/mobileconnectOFR/callback,
[[baseUrl]]/auth/v2/<your-app>/mobileconnectOES/callback,
[[baseUrl]]/auth/v2/<your-app>/mobileconnectOJO/callback,
[[baseUrl]]/auth/v2/<your-app>/mobileconnectOMG/callback,
[[baseUrl]]/auth/v2/<your-app>/mobileconnectOMA/callback

Some providers may require additional settings. For example: Google requires to configure the origins from which the authorization API is allowed to be called, or Facebook requires to publish your application before other users may access it.

[[service]] application settings

Now, you have to configure your [[service]] application within the "authentication" tab of the [[console]].

First, the appropriate OAuth2.0 provider(s) must be enabled. To configure an OIDC provider, you have to assign a (unique) identifier to it and to enter its Authorize, Token (and optionally Profile) URIs (these settings can be found in the provider documentation).

Next, the "client ID" and "client Secret" fields must be filled in with the corresponding values of your OAuth application:

Provider Where to find the client ID and secret
Facebook Click on "Dashboard" in the developer console of your OAuth application, and pick up the values of the "App ID" and "App Secret" fields.
Google Click on the previously created "OAuth client ID" in the "Identifiers" section, and pick up the values of the "Client ID" and "Client Secret" fields.
GitHub Click on the previously created OAuth application, and pick up the values of the "Client ID" and "Client Secret" fields.
GitLab Click on the previously created OAuth application, and pick up the values of the "Application Id" and "Secret" fields.
Orange France & Mobile Connect Orange Click on the "Summary" tab in the developer console of your OAuth application, and pick up the values of the "Client ID" and "Client Secret" fields.

Finally, you have to fill in the "authorized domains" cartridge with the domains from which your [[service]] application is allowed to invoke the OAuth2.0 authentication delegation API of [[service]]. These domains are divided into 2 parts:

  • the web domains, which constraint the hosts from which a web app is allowed to authenticate within your [[service]] application,
  • the Android apps, which constraint the Android application id of the Android apps that are allowed to authenticate within your [[service]] application.

Warning: iOS apps are currently not controlled, so that any iOS app can authenticate on your [[service]] application whatever its origin.

By default, no Android app is authorized and only 127.0.0.1 and localhost web domains are allowed for debug purposes. Don't forget to add your mobile apps id and the actual web domain(s) of your application servers before running in production.

Login with an OAuth2.0 provider

Once your OAuth application is properly configured with a given OAuth2.0 provider, you can use the following snippet in your [[service]] application to log a user in [[snippet]]:

// Create a connection to the back-end
var ref = new Webcom("<your-app>");
// Log in (uncomment the appropriate OAuth2.0 provider)
ref.authWithOAuth('facebook', function(error, auth) {
    if (error) {
      switch (error.code) {
        case "UNAUTHORIZED_REQUEST_ORIGIN":
          console.log("The domain of the application page is not properly registered in the [[console]].");
          break;
        case "PROVIDER_DISABLED":
          console.log("The OAuth2 login method is disabled for the requester provider in the application.");
          break;
        default:
          console.log("An unexpected error occurs, please retry and contact your administrator.", error);
      }
    } else {
      console.log("Authentication succeeded", auth);
    }
});
//ref.authWithOAuth('google', ...);
//ref.authWithOAuth('github', ...);
//ref.authWithOAuth('gitlab', ...);
//ref.authWithOAuth('orange', ...);
//ref.authWithOAuth('mobileconnectOFR', ...); // Mobile Connect Orange France
//ref.authWithOAuth('mobileconnectOES', ...); // Mobile Connect Orange Spain
//ref.authWithOAuth('mobileconnectOJO', ...); // Mobile Connect Orange Jordan
//ref.authWithOAuth('mobileconnectOMG', ...); // Mobile Connect Orange Madagascar
//ref.authWithOAuth('mobileconnectOMA', ...); // Mobile Connect Orange Morocco
//ref.authWithOAuth('oidc.<provider-identifier>', ...); // OIDC providers
try{
    // Create a connection to the back-end
    Webcom ref = new Webcom("[[baseUrl]]/base/<your-app>");
    // OAuth listener definition
    final OnOAuth listener = new OnAuthWithOAuth() {
        @Override
        public void onCancel( WebcomError error) {
            Log.d(TAG, "User cancels authentication");
        }
        @Override
        public void onComplete(AuthResponse response) {
            if (response == null) Log.d(TAG, "Logged out!")
            else Log.d(TAG, "Logged in: " + response.getIdentity().getDisplayName());
        }
        @Override
        public void onError(WebcomError error) {
            Log.e(TAG, "Authentication error: " + error.getMessage());
        }
    };
    ref.authWithOAuth(context, "orange", listener);
    //ref.authWithOAuth(context, "google", listener);
    //ref.authWithOAuth(context, "facebook", listener);
    //ref.authWithOAuth(context, "github", listener);
    //ref.authWithOAuth(context, "gitlab", listener);
    //ref.authWithOAuth(context, "mobileconnectOFR", listener); // Mobile Connect Orange France
    //ref.authWithOAuth(context, "mobileconnectOES", listener); // Mobile Connect Orange Spain
    //ref.authWithOAuth(context, "mobileconnectOJO", listener); // Mobile Connect Orange Jordan
    //ref.authWithOAuth(context, "mobileconnectOMG", listener); // Mobile Connect Orange Madagascar
    //ref.authWithOAuth(context, "mobileconnectOMA", listener); // Mobile Connect Orange Morocco
    //ref.authWithOAuth(context, "oidc.<provider-identifier>", listener); // OIDC providers
} catch (Exception e) {
    Log.e(TAG, e.getMessage(), e);
}
// Created connection to the back-end
WCWebcom * webcom = [[WCWebcom alloc]initWithURL:@"[[baseUrl]]/base/<your-app>"];

//Authentication thanks to OAuth2.0 protocol.
[webcom oAuth2Provider:"orange"
            onComplete:^(NSError * _Nullable error,
                        WCOAuth2UserInfoFromProvider * _Nullable authInfo) {
                //Do appropriate actions when this block is launched.
                      }
              onCancel:^(NSError * _Nonnull error) {
               //Do appropriate actions when this block is launched.
                      }];
// Created connection to the back-end
let webcom = WCWebcom.init(url:"[[baseUrl]]/base/<your-app>")

//Authentication thanks to OAuth2.0 protocol
webcom?.oAuth2Provider("orange",
                       onComplete: {error, authInfo in
                //Do appropriate actions when this block is launched.
                       },
                       onCancel: {error in
                //Do appropriate actions when this block is launched.
                       })

The authWithOAuth methods takes the name of the OAuth provider as first parameter. Possible values are : 'facebook', 'google', 'orange', 'mobileconnectOFR' (Mobile Connect Orange France), 'mobileconnectOES' (Mobile Connect Orange Spain), 'mobileconnectOJO' (Mobile Connect Orange Jordan), 'mobileconnectOMG' (Mobile Connect Orange Madagascar), 'mobileconnectOMA' (Mobile Connect Orange Morocco), 'github' or 'gitlab'. For OIDC providers, the name equals "oidc." plus the provider identifier assigned in the [[console]].
Also, the method admits an optional JSON structure with the following attributes (see Reference):

  • mode (string, optional, defaults to popup): authentication mode, among redirect (the authorization call-flow to the OAuth2.0 provider is invoked from the current window), popup (from a pop-up window) or code (no authorization call-flow is played).
  • scope (string, optional, defaults to ""): OAuth2.0 scope used during the authorization call-flow. If not set, an appropriate value is used, which asks the end user for the minimal required grant (see default scope). The allowed values depend on the OAuth2.0 providers, you have to consult their developer documentation for more details.

The auth parameter received by the authentication callback function is a JSON structure representing the identity used to log in. In addition to the generic fields, it includes the following ones:

Field Type Description
provider String Equals "facebook", "google", "github", "gitlab", "orange" or "mobileconnect" (lowercase).
Note that all Mobile Connect providers receive the same identifier, namely mobileconnect.
providerUid String The internal identifier of the authenticated end user used by the OAuth2.0 provider.
providerProfile Object An OAuth2.0 provider-specific structure providing some information about the authenticated end user. It generally includes her/his name and email address.
displayName String A human-readable description of the authenticated end user extracted from the previous profile data. It can be missing if no description can be found.
access_token String The OAuth2.0 access token got from the provider, which may be further used by your application to invoke some provider's APIs.

The authWithOAuth takes an activity context as first argument. This context is used by the SDK for opening a Web view with the authentication page of the targeted provider. The second argument is the name of the OAuth provider. Possible values are : "facebook", "google", "orange", "mobileconnectOFR" (Mobile Connect Orange France), "mobileconnectOES" (Mobile Connect Orange Spain), "mobileconnectOJO" (Mobile Connect Orange Jordan), "mobileconnectOMG" (Mobile Connect Orange Madagascar), "mobileconnectOMA" (Mobile Connect Orange Morocco), "github" or "gitlab". For OIDC providers, the name equals "oidc." plus the provider identifier assigned in the [[console]].
The last argument is a listener in charge of handling events from authentication.

Authentication events can be :

  • onCancel: when the user cancels the authentication (typically closes the authentication view by clicking the "back" button).
  • onComplete: when the user successfully logs in.
  • onError: when the authentication fails.

See the API reference for more details.

Once instantiation of the [[service]] connection is complete, the appropriate method defined above will do the job by displaying a view controller prompting the user to enter her/his login and password (cancelling the process is possible thanks to a cancel button).
Whatever the result, the completion of this action will be returned in the onComplete block including possible errors.
If the cancel button is pushed, the view controller is dismissed and the onCancel block is launched.

For further information about this method, take a look at the iOS SDK API.

If the identity used to log in is not bound to any [[service]] account, then a new account is automatically created (its id can be retrieved with the uid field) and the identity is bound to it.

Default scope used for each provider

Here is the default scope used with the authWithOAuth method when no scope parameter is specified. When you need a specific scope, don't forget to keep the default value appended to it.

Provider Default scope value
Facebook "public_profile,email"
Google "email profile"
GitHub "openid"
GitLab "openid"
Orange France "openid profile_limited"
Mobile Connect Orange "openid"
OIDC providers "openid"