Skip to content

Most visited

Recently visited

navigation

Authentication in Wear

With standalone watches in place, wear apps can now run entirely on a watch without a companion app. This new capability also means that Android Wear standalone apps will need to manage authentication on their own, when the apps need to access data from the cloud. Android Wear supports several authentication methods to enable standalone wear apps to obtain user authentication credentials.

Currently, Android Wear supports the following authentication methods:

The following sections describe how to integrate the above authentication methods into your Wear apps.

Google Sign-in

Google Sign-in enables the user to sign in with their existing Google account. It offers the best user experience and is easy to support, especially if you are already implementing these solutions in your handheld apps.

Google Sign-in is the most preferred solution as it also works well on iOS. The following section describes how to complete a basic Google Sign-in integration.

Prerequisites

Before you can start integrating Google Sign-In in your Wear app, you must configure a Google API Console project and set up your Android Studio project. For more information, see the Start Integrating guide for Google Sign-In.

Note: If you use Google Sign-In with an app or site that communicates with a backend server, then create an OAuth 2.0 web application client ID for your backend server. This client ID is different from your app's client ID. For more information, see Enabling Server-side Access.

Important: If your app communicates with a backend server, identify the currently signed-in user securely on the server by sending the user's ID token using HTTPS. To learn how to authenticate your user on the backend server, see Authenticate with a backend server.

Integrating Google Sign-in into your app

To integrate Google Sign-in into your Wear app:

  1. Configure Google Sign-in.
  2. Add a Google Sign-in button.
  3. Start the sign-in flow when the sign-in button is clicked.

Configure Google Sign-in and build the GoogleApiClient object

In your sign-in activity's onCreate method, configure Google Sign-in to request the user data required by your app. Then, create a GoogleApiClient object with access to Google Sign-in API and the options you specified.

// Configure sign-in to request the user's ID, email address, and basic
// profile. The ID and basic profile are included in DEFAULT_SIGN_IN.
// If you need to request additional scopes to access Google APIs, specify them with
// requestScopes().
GoogleSignInOptions.Builder signInConfigBuilder = new GoogleSignInOptions
        .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();

// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified in the sign-in configuration.
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this /* FragmentActivity */, this /OnConnectionFailedListener */)
        .addApi(Auth.GOOGLE_SIGN_IN_API, signInConfigBuilder)
        .build();

Add a Google Sign-In button to your app

  1. Add the SignInButton to your app's layout.
  2.  <com.google.android.gms.common.SignInButton
     android:id="@+id/sign_in_button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    
  3. In your app's onCreate() method , register your button's OnClickListener to sign in the user when clicked.
  4. findViewById(R.id.sign_in_button).setOnClickListener(this);
    

Create a Sign-in Intent and start the sign-in flow

When the sign-in button is clicked, handle sign-in button taps in your onCLick() method by creating a sign-in intent with the getSignInIntent method, and then starting the intent with the startActivityForResult method.

Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);

The user is prompted to select a Google account to sign in with. If you requested scopes beyond profile, email, and openid, the user is also prompted to grant access to those resources.

Finally, in the activity's onActivityResult method, retrieve the sign-in result with getSignInResultFromIntent. After you retrieve the sign-in result, you can check if the sign-in succeeded using the isSuccess method. If sign-in succeedes, you can call the getSignInAccount method to get a GoogleSignInAccount object that contains information about the signed-in user, such as the user's name.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...)
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult signInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (signInResult.isSuccess()) {
            GoogleSignInAccount acct = signInResult.getSignInAccount();

            // Get account information
            mFullName = acct.getDisplayName();
            mGivenName = acct.getGivenName();
            mFamilyName = acct.getFamilyName();
            mEmail = acct.getEmail();
        }
    }
}

To see a sample app that implements Google Sign-in, see the sample app.

OAuth 2.0 Support

Wear provides OAuth 2.0 support for third-party apps to authenticate a user with a web service. Considering the limited screen real estate on wear devices, Android Wear OAuth support enables standalone watch apps to complete the OAuth authentication flow via a phone. Standalone apps use a request and response URL model to authenticate a user and receive an OAuth token to access the service.

Note: If your Wear 2.0 app has an accompanying phone app, use the same package name for your Wear app and that phone app.

Prerequisites

Before you begin, create an OAuth 2.0 web application client ID for your backend server. This client ID is different from your app's client ID. You can find or create a client ID for your server in the Google API Console.

Flow

  1. The user performs an action with the third-party app, requiring authorization.
  2. The third-party app sends a request to the Android Wear companion app using the Wear services API, sendAuthorizationRequest(), to open a web view with the authorization URL.
  3. The URL website authorizes the user (asks the user for a username, password, perhaps does some two-factor authentication, etc.).
  4. After a successful or failed authorization, the site invokes the callback URL (to the app's backend server) specified in the request with the auth code.
  5. The backend server exchanges the auth code for access and refresh tokens from the OAuth server.
  6. The backend server then redirects the response to go to the third-party watch app via the Android Wear companion app.
  7. The Android Wear companion app receives that redirect and uses the Wearable support API, onAuthorizationResponse(), to send the entire response from the server back to the watch app.
  8. The third-party app parses the response from the auth site and extracts an auth token from the response.
  9. The third-party app uses the auth token as a credential in its future requests.
alt_text

To implement the above auth flow, you need to do the following:

  1. Create a client ID and client secret.
  2. Perform an auth request.
  3. Handle the auth response.

Create a client ID and client secret

Wear apps that use OAuth 2.0 must create a client ID and client secret that identify the application to an OAuth provider. You need to set up an API console project to obtain these credentials.

Perform a auth request

To perform an auth request to an OAuth provider, first create a client object that you will use to make OAuth 2.0 requests in your onCreate() method.

Note: To ensure that your app doesn’t shut down when the watch goes into ambient mode, enable Always-on (via setAmbientEnabled) in your app’s OAuth activity. For more information on best practices in ambient mode, see the Keeping Your App Visible page.

@Override
public void onCreate(Bundle b) {
    super.onCreate(b);
    mOAuthClient = OAuthClient.create(this);
    …...
}

Next, build a URL that includes an OAuth endpoint for getting a token, your server OAuth client ID, the redirect URL (to your backend server), and the response type .

The requested URL is similar to the following:

https://accounts.google.com/o/oauth2/v2/auth?response_type=code
&client_id="your_client_id_here";
&scope=https://www.googleapis.com/auth/plus.login
&redirect_uri=https://myserver.com

After you build the auth request, you can send the request to the companion app using the Wear services API, sendAuthorizationRequest().

This request triggers an RPC to the companion, which causes an authorization UI to be presented on the user's phone. The OAuth 2.0 provider authenticates the user and obtains the user's consent for your application to access the requested scopes. The response is sent back to your backend server using the redirect URL you specified.

Handle the auth response

After a successful or failed authorization, the OAuth 2.0 server redirects to the URL specified in the request. If the user approves the access request, then the response contains an authorization code. If the user does not approve the request, the response contains an error message.

The response will be of a query string form, as shown below:

https://myserver.com/oauthtokens?code=xyz

After the backend server receives the authorization code, it can exchange the authorization code for an access token. Then the backend server returns an HTTP 302 redirect to the Android Wear phone app that registered as a receiver for URLs of the form: https://wear.googleapis.com/3p_auth/app.html?full_suffix_from_redirect=com.your.package.name?accessToken=abc&refreshToken=xyz.
The phone app verifies the response URL and relays the response to the third-party watch app using the onAuthorizationResponse API.

Note:Make sure that the app package name is the 3rd path component in the redirect URL. So, the redirect_uri must be equal to https://wear.googleapis.com/3p_auth/<receiving app's packagename>. For example, https://wear.googleapis.com/3p_auth/com.package.name.

The third-party app on the watch extracts the auth token from the response and uses the auth token as a credential in its future requests.

// The callback provided will be called when the OAuth request completes.
mClient.sendAuthorizationRequest(Uri.parse(requestUrl), new MyOAuthCallback());
private class MyOAuthCallback extends OAuthClient.Callback {
    @Override
    public void onAuthorizationResponse(Uri requestUrl, Uri responseUrl) {
        super.onAuthorizationResponse(requestUrl, responseUrl);
        Runnable r =
            new Runnable() {
                public void run() {
                    acquireToken();
                    accessAPI();
                }
            };
    }
}

To see a complete implementation of this flow, see the sample.

Note: For the purposes of this sample, the watch is handling the token exchange. As a best practice, set the redirect URI to your own server URL, where the server can perform the authorization code token exchange.

Pass Tokens via Data Layer

This option works only for Android-paired watches. The companion app on the phone can securely transfer authentication data to the Wear app via the Wearable Data Layer. The credentials can be transferred as messages or data items.

Note: We recommend delivering your phone APK and watch APK using the same package name. This allows the phone and wear apps to communicate via the DataItem layer and do the background token transfer from the phone to the watch to provide authentication.

Flow

You can use your own business logic to pass the credentials using the Data Layer API. The following diagram illustrates one of the ways to get the tokens via Wearable Data Layer.

alt_text

Custom Code Authentication

This authentication method requires the user to authenticate from an external source (mobile device/ tablet / pc) and obtain a short-lived code that they enter to prove their identity and exchange it for an auth token on their wear device. In this method, you can authenticate users to your Wear app by either using your app’s login module or by manually integrating any third-party auth provider sign-in method into your app’s code. Although this authentication method requires manual work and additional effort to make it more secure, if you need authentication earlier on in your standalone Wear apps, you can use this method.

The auth flow for this setup works as follows:

  1. The user performs an action with the third-party app requiring authorization.
  2. The third-party Wear app presents an authentication screen to the user and instructs the user to enter a code from a specified URL.
  3. The user switches to a mobile device / tablet or PC, launches a browser, navigates to the URL specified on the Wear app, and logs in.
  4. The user receives a short-lived code that they enter into the Wear app authentication screen using the onboard keyboard in Wear to get authenticated:

    alt_text

  5. From this point, you can use the entered code as proof that this is the correct user, and exchange that for an auth token stored and secured on the wear device for authenticated calls going forward.
alt_text
This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)