Developer Console
Gracias por tu visita. Esta página solo está disponible en inglés.

Use Login with Amazon SDK with Android

II: Integrate LwA in your apps

~
~

Follow the instructions below to use the Login with Amazon SDK for Android to pass the Login with Amazon authorization code, client ID, and redirect URI to your product. Your product can then use this data to obtain the refresh and access token needed to make calls to DRS. The full sample code is available in the Amazon Dash GitHub repository

LWA Version Note

Note that in this documentation, we are using LWA version 3.0.0. You can check the LWA version by following the steps under What version of the Login with Amazon SDK for Android is my app using.

The output should look similar to this:

LWA_VERSION = "3.0.0";

Get the Authorization Code and Make Calls to DRS on Android

  1. Navigate to Login with Amazon Getting Started for Android and complete steps 1 through 5.
Teaser page

On step 5, you will be asked to add a "Login with Amazon" button. You should customise the look and feel of the button as per our Teaser page guidelines
  1. Obtain a new API key from the Security Profiles console. If you do not have a Security Profile, follow the steps in the Create an LWA Security Profile guide to create one.
  2. In Security Profile Management, under your security profile, select Android/Kindle Settings.

  3. Fill in the required fields to register your application.
  4. Click Show under the Key column to see your API key.

  5. Copy the API key to your application’s api_key.txt file.
  6. Import the LWA API to your source file by adding the following statements:

    import com.amazon.identity.auth.device.AuthError;
    import com.amazon.identity.auth.device.api.authorization.AuthCancellation;
    import com.amazon.identity.auth.device.api.authorization.AuthorizationManager;
    import com.amazon.identity.auth.device.api.authorization.AuthorizeListener;
    import com.amazon.identity.auth.device.api.authorization.AuthorizeRequest;
    import com.amazon.identity.auth.device.api.authorization.AuthorizeResult;
    import com.amazon.identity.auth.device.api.authorization.Scope;
    import com.amazon.identity.auth.device.api.authorization.ScopeFactory;
    import com.amazon.identity.auth.device.api.workflow.RequestContext;
    
  7. Declare the RequestContext object as the class variable and initialize it in the onCreate() method:

    private RequestContext requestContext;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     requestContext = RequestContext.create(this);
    }
    
  8. Register a new AuthorizeListener to the RequestContext object:

    requestContext.registerListener(new AuthorizeListener() {
    
     /* Authorization was completed successfully. */
     @Override
     public void onSuccess(final AuthorizeResult authorizeResult) {
      runOnUiThread(new Runnable() {
       @Override
       public void run() {
        Log.d(TAG, authorizeResult.getRedirectURI());
        Log.d(TAG, authorizeResult.getAuthorizationCode());
        Log.d(TAG, authorizeResult.getClientId());
       }
      });
     }
    
     /* There was an error during the attempt to authorize the application */
     @Override
     public void onError(AuthError authError) {
      runOnUiThread(new Runnable() {
       @Override
       public void run() {
        Log.e(TAG, "Error during authorization. Please try again.");
       }
      });
     }
    
     /* Authorization was cancelled before it could be completed. */
     @Override
     public void onCancel(AuthCancellation authCancellation) {
      runOnUiThread(new Runnable() {
       @Override
       public void run() {
        Log.i(TAG, "Authorization cancelled.");
       }
      });
     }
    });
    

    The methods onSuccess(), onError(), and onCancel() should contain the code with their respective login scenarios.

  9. Add the following code to the onResume() method:

    @Override
    protected void onResume() {
     super.onResume();
     requestContext.onResume();
    }
    
  10. In order to perform the authorization, include the following lines in your application:

    AuthorizationManager.authorize(
     new AuthorizeRequest.Builder(requestContext)
     .addScopes(YOUR-LOGIN-SCOPE)
     .forGrantType(AuthorizeRequest.GrantType.AUTHORIZATION_CODE)
     // Set your code challenge and code challenge method - "plain" or "S256".
     .withProofKeyParameters(YOUR_CODE_CHALLENGE,
      YOUR_CODE_CHALLENGE_METHOD)
     .build()
    )
    

    For more information about YOUR_CODE_CHALLENGE and YOUR_CODE_CHALLENGE_METHOD please see the prerequisites section. An example would be a login button:

    /**
    * Initializes all of the UI elements in the activity.
    */
    private void initializeUI() {
        mLoginButton = findViewById(R.id.login_with_amazon);
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Scope scope = getScope();
                if (scope != null) {
                    AuthorizationManager.authorize(
                            new AuthorizeRequest.Builder(requestContext)
                                    .addScopes(scope)
                                    .forGrantType(AuthorizeRequest.GrantType.AUTHORIZATION_CODE)
                                    // Set your code challenge and code challenge method - "plain" or "S256".
                                    .withProofKeyParameters(YOUR_CODE_CHALLENGE, YOUR_CODE_CHALLENGE_METHOD)
                                    .build()
                    );
                }
            }
    
        });
    }
    
    /**
    * Get the login scope.
    *
    * @return Scope.
    */
    private Scope getScope() {
      //YOUR_DEVICE_MODEL_NAME - The model ID of your device obtained from self-service portal.
      //YOUR_DEVICE_SERIAL_NUMBER – The serial number of the device you are associating with the DRS service. Only alphanumeric characters can be used [A-Za-z0-9], for a maximum string length of 50 characters.
      //IS_THIS_A_TEST_DEVICE – Flag that indicates if this a test device or not. You will not be able to test devices without setting the `is_test_device` flag to true, but you must set it to false in production. Test devices will not place real orders
      // SHOULD_INCLUDE_NON_LIVE if true, allows the registration to proceed using device capabilities that have not yet been certified by Amazon. You can use this parameter to test your system while awaiting Amazon certification.
        final String scopeDataString = "{\"device_model\":\"" + YOUR_DEVICE_MODEL_NAME +
                "\", \"serial\":\"" + YOUR_DEVICE_SERIAL_NUMBER +
                "\", \"is_test_device\":\"" + IS_THIS_A_TEST_DEVICE +
                "\", \"should_include_non_live\":\"" + SHOULD_INCLUDE_NON_LIVE +
                "\"}";
        JSONObject scopeData;
        try {
            scopeData = new JSONObject(scopeDataString);
            return ScopeFactory.scopeNamed("dash:replenish", scopeData);
        } catch (JSONException e) {
            Log.e(TAG, "Error during scope data JSON object creation", e);
        }
        return null;
    }
    

    The following table summarizes the configuration required for should_include_non_live and is_test_device in 3 different phases: during testing, when you submit for certification and when you go live in production.

    Attribute Test Certification Production
    should_include_non_live true true false
    is_test_device true false false
  11. After a successful login, the AuthorizeListener onSuccess() method is called. You should obtain the authorization code, client ID, and redirect URI and securely transfer them to your back-end, using SSL.
  12. After the authorization code, client ID, and redirect URI are received by your back-end, the server can call Login with Amazon to exchange the authorization code for the access token and refresh token .

The following steps will walk you through the process of making this call. This call can be made from your mobile application or DRS product or by your backend solutions. (In this documentation, we assume you will make that call on your cloud.)

Obtain Refresh and Access Tokens using Authorization Code Grant

When making the call, the product needs to send a POST request to https://api.amazon.com/auth/O2/token and pass in the following parameters:

HTTP Header Parameters

  • Content-Type: application/x-www-form-urlencoded

HTTP Body Parameters

  • grant_type: authorization_code.
  • code: The authorization code string received from the Android app.
  • redirect_uri: The redirect URI string received from the Android app.
  • client_id: The client ID string received from the Android app.
  • code_verifier: The code verifier string that was initially generated by the product.

Sample Request:

 POST /auth/o2/token HTTP/1.1
 Host: api.amazon.com
 Content-Type: application/x-www-form-urlencoded
 Cache-Control: no-cache
 code=YOUR-AUTHORIZATION-CODE&client_id=YOUR-CLIENT-ID&redirect_uri=YOUR-REDIRECT-URI&code_verifier=YOUR-CODE-VERIFIER&grant_type=authorization_code
 curl –X POST –d 'code=YOUR-AUTHORIZATION-CODE&client_id=YOUR-CLIENT-ID&redirect_uri=YOUR-REDIRECT-URI&code_verifier=YOUR-CODE-VERIFIER&grant_type=authorization_code' https://api.amazon.com/auth/O2/token

The response includes the following values:

  • access_token: The access token string.
  • refresh_token: The refresh token string.
  • token_type: The token type string.
  • expires_in: The number of seconds for which the access token is still valid.

Sample Response:

 HTTP/1.1 200 OK

 {
    "access_token": "Atza|IQEBLjAsAhRBejiZKPfn5HO2562GBt26qt23EA...",
    "expires_in": 3600,
    "refresh_token": "Atzr|IQEBLzAtAhUAibmh-1N0EsdqwqwdqdasdvferrE...",
    "token_type": "bearer"
 }

Request New Refresh and Access Tokens

The access token is valid for one hour. When the access token expires, or is about to expire, you can exchange the refresh token for a new access token.

  • Send a POST request to https://api.amazon.com/auth/o2/token with the following parameters:

HTTP Header Parameters

  • Content-Type: application/x-www-form-urlencoded

HTTP Body Parameters

  • grant_type: refresh_token
  • refresh_token: The refresh token used to request new access tokens.
  • client_id: The client ID string received from the Android app.
  • client_secret: The security profile's client secret. This information can be found on the Amazon developer portal’s Login With Amazon page.

Sample Request

POST /auth/o2/token HTTP/1.1
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
grant_type=refresh_token&refresh_token=Atzr|CIQEBLzAtAhUAibmh-1N0E&client_id=amzn1.application-oa2-
client.b91a...&client_secret=6963038c1c2063c33ab9eedc...

Sample Response

HTTP/1.1 200 OK
{
   "access_token": "Atza|IQEBLjAsAhQ3yD47Jkj09BfU_qgNk4...",
   "expires_in": 3600,
   "refresh_token": "Atzr|IQEBLzAtAhUAibmh-1N0EVztZJofMx...",
   "token_type": "bearer"
}

Next Step

Next, we will look at integrating Login with Amazon in your other companion apps.

To create… Use
A native Android app LwA SDK for Android
A native iOS app LwA SDK for iOS
A web app or hybrid app (e.g. Cordova) LwA for Web

If you have integrated LwA already, you may move onto the API section of our tutorial.


Last updated: Aug 07, 2018