A JBoss Project
Red Hat

Aerogear Guides Tutorials to help get you off and running.

OAuth2 Guide

Overview

Support of OAuth2 for Keycloak, Google and Facebook on our Android, iOS, Windows and Cordova platforms.

Flows Android iOS JavaScript Cordova Windows Phone

Authorization Code Grant

-

Implicit grant flow

-

-

-

soon

-

Refresh access tokens

-

Token revocation

-

-

-

-

Resource owner password credentials grant

-

soon

-

-

-

Below are the various GitHub repositories that are part of the OAuth2 feature in AeroGear.

Android

The AeroGear Android Authz will give developers the ability to integrate their Android application with RESTful services secured with OAuth2.

Apache Cordova

Our Apache Cordova plugin for OAuth2 supports the following platforms:

  • Android

  • iOS

  • Windows

iOS

On iOS we do have a Swift based OAuth2 client library.

Windows

For Windows we have a client library for OAuth2 on Windows phone.

Demo applications

We have a demo application, called Shoot’n Share for all of our supported platforms (Android, iOS, Windows and Cordova). The application allows you to upload a photo to Facebook, Google+ or a Keycloak protected backend.

The different applications can be found it the platform specific cookbooks:

The Keycloak protected backend application is a simple Java EE / JAX-RS based application. The source is located here.

Before you get started

The OAuth2 examples described in this guide require some previous setup to make Keycloak, Facebook and Google work. Please follow the steps listed below.

Google Account Setup

  1. First, you must authenticate with Google. You will need a Google Account for this. Now open the Google Console.

  2. If you haven’t created a project, click "Create Project" and give the new project a name:

    Google Console - Create Project

  3. Now you enable the Drive API. To do that, navigate to APIs & auth > APIs and scroll down to the Drive API item, which you need to turn on:

    Google Console - Enable APIs

  4. Create new credentials to access your Drive accounts from the app. Go to APIs & auth > Credentials and inside OAuth area click the blue Create new Client ID button.

    Google Console - Create client ID

  5. You will need to create a consent screen. Click the blue Configure consent screen

    Google Console - Consent screen
  6. Afterwards, click save and you will return to the Client ID. Select Installed application and iOS and fill in your bundle ID, these settings will work for Android and iOS:

    Google Console - Create client ID

  7. On the last screen we finally get to see the actual value of the generated client id, secret id and redirect uris, which you will use later:

    Google Console - Credentials

Facebook Account Setup

  1. First you must have a Facebook account. Now open the Facebook Developers page and select AppsAdd a New App

    Facebook - Add App

  2. Create a new app and select Website as platform

    Facebook - Select platform

  3. Click Skip and Create App ID

    Facebook - Skip and Create App ID

  4. Setup a Display Name and Namespace and select a category, then click Create App ID

    Facebook - Choice app category

  5. Fill out the captcha

  6. Now on the Dashboard view. Make a note of your App ID and App Secret.

    Facebook - Dashboard

  7. Select Settings from the sidebar and then the Advanced tab

    Facebook - Advanced Tab

  8. Scroll to Security and enable Embedded browser OAuth Login and make https://localhost/ your redirectURI

    Facebook - Enable OAuth

    Now save your changes and Facebook is ready to go.

Keycloak

  1. Download Keycloak Appliance Distribution version 1.1.0.Final

  2. Start the server

    $ KEYCLOAK_APPLIANCE_HOME/keycloak/bin/standalone.sh -b 0.0.0.0

    A quick screencast can be seen here.

  3. Open http://localhost:8080/auth/admin/index.html

    Keycloak - Login page

  4. Login using Username: admin / Password: admin

  5. Insert a new password

  6. Click on Add realm

    Keycloak - Realm configuration

  7. Import the realm configuration file

Getting started

AeroGear integrates with several OAuth2 providers. If you already have an existing mobile application, please select a platform and follow one of the steps below.

All the examples described here are based on our demo application, called Shoot’nShare.

Server side deployment

Most of the examples do not require an application server to work, but if you’re planning to use Keycloak as security provider, WildFly is required.

Assuming that all the instructions described here were properly followed, now deploy our example server:

$ git clone git@github.com:aerogear/aerogear-backend-cookbook.git && cd aerogear-backend-cookbook
$ cd Shoot
$ mvn clean install
$ mvn wildfly:deploy

Keep in mind that the example server is not required to connect with Keycloak. Shoot’nShare server only showcase an end-to-end security integration in real life and display the uploaded photos.

Android

To download one of our examples, check our cookbooks.

  1. Adding AeroGear to the project

    compile ('org.jboss.aerogear:aerogear-android-authz:2.0.0') {
        exclude module : 'compatibility-v4'
        transitive = true
    }
  2. Add the android.permission.INTERNET permission:

    <uses-permission android:name="android.permission.INTERNET"/>
  3. Then add the following entries to AndroidManifest.xml inside the <application> tag:

    <application>
        <service android:name="org.jboss.aerogear.android.authorization.oauth2.OAuth2AuthzService"/>
    </application>
  4. Initialise the AuthorizationManager.

    First create a helper class and add these lines of code:


    Copy & paste
    AuthorizationManager.config("KeyCloakAuthz", OAuth2AuthorizationConfiguration.class)
            .setBaseURL(new URL("http://localhost:8080/auth"))
            .setClientId("shoot-third-party")
            .setAuthzEndpoint("/realms/shoot-realm/tokens/login")
            .setAccessTokenEndpoint("/realms/shoot-realm/tokens/access/codes")
            .setRefreshEndpoint("/realms/shoot-realm/tokens/refresh")
            .setAccountId("keycloak-token")
            .setRedirectURL("http://oauth2callback")
            .asModule();
    

    Please make sure to use the proper client ID and client secret for your application.

  5. Create a model class

    The Android library will automatically marshall the HTTP request payload from OAuth2 providers. For more detailed information, please visit the Android documentation.

    public class PhotoHolder {
    
        @RecordId
        private String id = null;
    
        private String title, message;
        private File image;
        //getters and setters
    }
  6. PipeManager configuration

    Now you can configure the PipeManager to make use of the AuthorizationManager previously initialised.


    Copy & paste
    PipeManager.config("kc-upload", RestfulPipeConfiguration.class)
            .module(AuthorizationManager.getModule("KeyCloakAuthz"))
            .withUrl(new URL("http://localhost:8080/shoot/rest/photos"))
            .requestBuilder(new MultipartRequestBuilder())
            .forClass(PhotoHolder.class);
    

    Please make sure to use the proper client ID and client secret for your application.

  7. Request access

    Finally, you need to request access to the OAuth2 provider. Make sure to create a new method for the helper class and inform the module name. The possible values are: KeyCloakAuthz, FacebookOAuth and GoogleDriveAuthz.

    final AuthzModule authzModule = AuthorizationManager.getModule(<module name>);
    
    authzModule.requestAccess(activity, new Callback<String>() {
        @Override
        public void onSuccess(String s) {
            callback.onSuccess(s);
        }
    
        @Override
        public void onFailure(Exception e) {
            if (!e.getMessage().matches(OAuthWebViewDialog.OAuthReceiver.DISMISS_ERROR)) {
                authzModule.deleteAccount();
            }
            callback.onFailure(e);
        }
    });
  8. You are legendary!

    Congratulations, we’re done here! You followed all the steps to heaven and now it’s time to celebrate.

Apache Cordova

To download one of our examples, check our cookbooks.

  1. Adding AeroGear to the project

    $ cordova plugin add aerogear-cordova-oauth2
  2. Configure Info.plist file

    Add the CFBundleURLTypes key or skip this step if you have no plans to connect with Facebook or deploy on iOS.

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>org.aerogear.Shoot</string>
                <string>fbYYY</string>
            </array>
        </dict>
    </array>
  3. Add the OAuth2 provider configuration


    Copy & paste
    oauth2.addKeycloak({
      name: 'keycloak',
      settings: {
        base: '',
        //when you use the shoot and share backend these do not need to change
        clientId: 'shoot-third-party',
        realm: 'shoot-realm'
      }
    });
    

    Please make sure to use the proper client ID and client secret for your application.

  4. Deploy

    $ cordova run android
    
  5. You are legendary!

    Congratulations, we’re done here! You followed all the steps to heaven and now it’s time to celebrate.

iOS

To download one of our examples, check our cookbooks.

  1. Adding AeroGear to the project

    pod 'AeroGearHttp', '0.2.0'
    pod 'AeroGearOAuth2', '0.2.1'
  2. Configure Info.plist file

    Add the CFBundleURLTypes key or skip this step if you have no plans to connect with Facebook.

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>org.aerogear.Shoot</string>
                <string>fbYYY</string>
            </array>
        </dict>
    </array>
  3. Create a ViewController class and instantiate the Http class

    For more detailed information about the HTTP module, please visit the iOS documentation.

    var Http = Http()
  4. Initialise the OAuth2 provider configuration


    Copy & paste
    let keycloakHost = "http://localhost:8080"
    let keycloakConfig = KeycloakConfig(
        clientId: "shoot-third-party",
        host: keycloakHost,
        realm: "shoot-realm")
    

    Please make sure to use the proper client ID and client secret for your application.

  5. Add the OAuth2 configuration to the AccountManager


    Copy & paste
    let keycloakModule = AccountManager.addKeycloakAccount(keycloakConfig)
    
  6. Inject the OAuth2 module into HTTP object


    Copy & paste
    self.http.authzModule = keycloakModule
    
  7. Create a method to send the HTTP request

    Finally, send an HTTP request to make sure that everything is fine. Make sure to create a separate method for this.

    func performUpload(url: String, parameters: [String: AnyObject]?) {
        self.http.POST(url, parameters: parameters, completionHandler: {(response, error) in
            if (error != nil) {
                self.presentAlert("Error", message: error!.localizedDescription)
            } else {
                self.presentAlert("Success", message: "Successfully uploaded!")
            }
        })
    }
  8. You are legendary!

    Congratulations, we’re done here! You followed all the steps to heaven and now it’s time to celebrate.

Windows Phone

To download one of our examples, check the sources.

  1. Application configuration

    Go to Visual Studio and open Package.appxmanifest go to Declarations add a protocol and set the bundle id you picked on the google console.

    Protocol configuration

    Next step is setting up the account in code, replace the <google-client-id> with your google client id.

  2. Initialise the OAuth2 provider configuration

    var config = await GoogleConfig.Create(
        "<google-client-id>",
        new List<string>(new string[] { "https://www.googleapis.com/auth/drive" }),
        "google"
    );
  3. Add the OAuth2 configuration to the AccountManager

    var googleModule = await AccountManager.AddAccount(config);
  4. Request access

    if (await module.RequestAccessAndContinue())
    {
        Upload(module);
    }

    if the result is true the app will not be suspended and we can for instance upload to Google Drive, like in this example. Otherwise the app will be suspended and an authentication dialog will appear.

    To handle the continuation event, include continuation manager in you app. Or implement everything by yourself:

    protected async override void OnActivated(IActivatedEventArgs args)
    {
        if (args.Kind == ActivationKind.WebAuthenticationBrokerContinuation)
        {
            //get a reference to the page as IWebAuthenticationContinuable
            var wabPage = rootFrame.Content as IWebAuthenticationContinuable;
            wabPage.ContinueWebAuthentication(args as WebAuthenticationBrokerContinuationEventArgs);
        }
    ...

    The page will have to implement the IWebAuthenticationContinuable interface like this:

    async void IWebAuthenticationContinuable.ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
    {
        Upload(await AccountManager.ParseContinuationEvent(args));
    }

    This will parse the ContinuationEvent and save the token from the OAuth provider (in this case Google) to the device. So the next time user don’t need to authenticate again.

    In the upload method, make use of AuthzWebRequest, a special WebRequest that will take care of adding the authentication headers.

    public async void Upload(OAuth2Module module)
    {
        var request = AuthzWebRequest.Create("https://www.googleapis.com/upload/drive/v2/files", module);
        request.Method = "POST";
    
        using (var postStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
    ...
  5. You are legendary!

    Congratulations, we’re done here! You followed all the steps to heaven and now it’s time to celebrate.

What’s next?

We’re constantly improving our API, based on the the open source community, if you think something is missing, file a Jira.

Want to learn more? Go back to our guides.

Asking for help

Security can be tricky sometimes, due to numerous misunderstandings and subtle details behind it, so feel free to reach out to us if you have any questions or want to provide honest feedback.

redhatlogo-wite