Use the Login with Amazon SDK for iOS APIs
- Connect the AppDelegate
- Handle the Login Button and Get Profile Data
- Fetch User Profile Data
- Check for User Login at Startup
- Clear Authorization Data and Log Out Users
- Test your Integration
Connect the AppDelegate
Implement application:openURL:options:
in the class in your project that handles the UIApplicationDelegate
protocol. By default, this will be the AppDelegate
class. When a user successfully logs into your app using Login with Amazon, they will be redirected from the Amazon login screen back to your app based on the URL Scheme you added to your App Property List earlier. In order to handle this redirect, you must implement the application:openURL:options:
method, which returns YES
if the URL is successfully handled.
The Login with Amazon SDK for iOS provides a library function, handleOpenURL:sourceApplication:
which handles any redirect URL
sent from Amazon pages. It returns YES
if the URL is successfully handled by the SDK. Call this method within the application:openURL:options:
method.
To invoke this method, you will need to import <LoginWithAmazon/LoginWithAmazon.h>
.
import <LoginWithAmazon/LoginWithAmazon.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)
url options:(NSDictionary<uiapplicationopenurloptionskey,id> *)options {
return [AMZNAuthorizationManager handleOpenURL:url
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
}
@end
Handle the Login Button and Get Profile Data
This section explains how to call the authorize:withHandler:
API to login a user. This includes creating an onLoginButtonClicked:
listener for your Login with Amazon button.
-
Add Login with Amazon to your iOS project. For instructions, see Create a Login with Amazon Project.
-
Import the Login with Amazon API to your source file.
To import the Login with Amazon API, add the following #import statements to your source file:
#import <LoginWithAmazon/LoginWithAmazon.h>
-
Call
authorize:withHandler:
inonLoginButtonClicked
.If you followed the steps in Add a Login with Amazon Button to Your App, you should have an
onLoginButtonClicked:
method linked to a Login with Amazon button. In that method, callauthorize:withHandler:
to prompt the user to login and authorize your application.This method will enable the user to sign in and consent to the requested information in one of the following ways:
- Switches to web view in a secure context (if the Amazon Shopping app is installed to the device)
- Switches to Safari View Controller (on iOS 9 and later)
- Switches to the system browser (on iOS 8 and earlier)
The secure context for the first option is available when the Amazon Shopping app is installed to the device. If the user is already signed in to the Amazon Shopping app, this API will skip the sign in page, leading to a Single Sign-On (SSO) experience. See Customer Experience for iOS apps to learn more.
The first parameter to
authorize:withHandler:
is anAMZNAuthorizeRequest
object that indicates what scope your application is requesting authorization for. A scope encompasses the user data you are requesting from Login with Amazon. The first time a user logs in to your app, they will be presented with a list of the data you are requesting and asked for approval.Login with Amazon currently supports the following scopes:
profile
(gives access to the user’s name, email address, and Amazon account ID),profile:user_id
(gives access to the user’s Amazon account ID only), andpostal_code
(gives access to the user’s zip/postal code on file for their Amazon account).Use the methods defined in
AMZNProfileScope
to get a scope object and add it to yourAMZNAuthorizeRequest
object. See the sample code below for details.The second parameter to
authorize:withHandler:
isAMZNAuthorizationRequestHandler
, described in the next step. -
Create an
AMZNAuthorizationRequestHandler
block object.AMZNAuthorizationRequestHandler
processes the result of theauthorize:withHandler:
call. To learn more about objective-c blocks, see Working with Blocks on developer.apple.com.The first parameter of
AMZNAuthorizationRequestHandler
is anAMZNAuthorizeResult
object. After a user is authorized successfully,AMZNAuthorizeResult
will contain an access token which can be used to access a user’s profile data, and anAMZNUser
object, which contains the user’s profile data.The second parameter of
AMZNAuthorizationRequestHandler
is a Boolean calleduserDidcancel
. This parameter will be set to true if the user:- Closes the Safari View Controller during login and authorization (on iOS 9 and later)
- Closes the sign in or consent screens from the web view in the Amazon Shopping app
- Cancels the login or rejects authorization
The third parameter of
AMZNAuthorizationRequestHandler
is anNSError
object which contains error details if the login and authorization fails due to the SDK or authorization server.- (IBAction)onLogInButtonClicked:(id)sender { // Build an authorize request. AMZNAuthorizeRequest *request = [[AMZNAuthorizeRequest alloc] init]; request.scopes = [NSArray arrayWithObjects: // [AMZNProfileScope userID], [AMZNProfileScope profile], [AMZNProfileScope postalCode]]; // Make an Authorize call to the Login with Amazon SDK. [[AMZNAuthorizationManager sharedManager] authorize:request withHandler:^(AMZNAuthorizeResult *result, BOOL userDidCancel, NSError *error) { if (error) { // Handle errors from the SDK or authorization server. } else if (userDidCancel) { // Handle errors caused when user cancels login. } else { // Authentication was successful. // Obtain the access token and user profile data. NSString *accessToken = result.token; AMZNUser *user = result.user; NSString *userID = user.userID; } }]; }
Fetch User Profile Data
As long as a user is logged in and authorized to your app, you can fetch their user profile data at any time. This section explains how to use the fetch:
method of the AMZNUser
class to retrieve the most up-to-date user profile data for users who are currently authorized. The profile data you can retrieve is based on the scope indicated in the authorize
call.
-
Call
AMZNUser fetch:
.This method will fetch profile data via an
AMZNUserFetchRequestHandler
block object. The first parameter toAMZNUserRequestHandler
is anAMZNUser
object. TheAMZNUser
object can include auserID
,name
,email
, andpostalCode
, depending on the requested scope.[AMZNUser fetch:^(AMZNUser *user, NSError *error) { if (error) { // Error from the SDK, or no user has authorized to the app. } else if (user) { NSString *userID = user.userID; //NSString *name = user.name; //NSString *email = user.email; //NSString *postalCode = user.postalCode; } }];
Check for User Login at Startup
If a user logs into your app, closes the app, and restarts the app later, the app is still authorized to retrieve data. The user is not logged out automatically. At startup, you can show the user as logged in if your app is still authorized. This section explains how to use authorize:withHandler:
to see if the app is still authorized.
-
Create an
AMZNAuthorizeRequest
object and specify scopes that indicate the user data your application is requesting authorization for. For more information on scopes, see Handle the Login Button and Get Profile Data above. -
Set
AMZNAuthorizeRequest.interactiveStrategy
toAMZNInteractiveStrategyNever. AMZNAuthorizeRequest
supports multiple strategies for prompting user login:AMZNInteractiveStrategyAuto
(default): The SDK looks for a locally stored authorization grant from previousauthorize:withHandler:
responses. If one is available, valid, and contains all requested scopes, the SDK will return a successful response viaAMZNAuthorizationRequestHandler
, and will not prompt the user to login. Otherwise, the user will be prompted to login.AMZNInteractiveStrategyAlways:
The SDK will always prompt the user to login regardless of whether they have previously been authorized to use the app. When the user is prompted, the SDK will remove all locally cached authorization grants for the app.AMZNInteractiveStrategyNever:
The SDK looks for a locally stored authorization grant from previousauthorize:withHandler
responses. If one is available, valid, and contains all requested scopes, the SDK will return anAMZNAuthorizeResult
object that contains an access token and user profile data. Otherwise, it will return anNSError
object viaAMZNAuthorizationRequestHandler
.
// Build an authorize request. AMZNAuthorizeRequest *request = [[AMZNAuthorizeRequest alloc] init]; request.scopes = [NSArray arrayWithObjects: // [AMZNProfileScope userID], [AMZNProfileScope profile], [AMZNProfileScope postalCode]]; request.interactiveStrategy = AMZNInteractiveStrategyNever; [[AMZNAuthorizationManager sharedManager] authorize:request withHandler:^(AMZNAuthorizeResult *result, BOOL userDidCancel, NSError *error) { if (error) { // Error from the SDK, indicating the user was not previously authorized to your app for the requested scopes. } else { // The user was previously authorized to your app. // Obtain the access token and user profile data. NSString *accessToken = result.token; AMZNUser *user = result.user; NSString *userID = user.userID; } }];
Clear Authorization Data and Log Out Users
This section explains how to use the signOut
method to clear the user's authorization data from both the AMZNMobileLib
(AMZNMobileLib
was renamed from AIMobileLib
in Login with Amazon for iOS version 3.1.0) local data store, and the authorization server. The user will have to login again in order for the app to retrieve profile data. Use this method to log out a user, or to troubleshoot login problems in the app.
-
Implement a logout mechanism.
When a user has successfully logged in, you should provide a logout mechanism so they can clear their profile data and previously authorized scopes. Your mechanism might be a hyperlink, button, or a menu item.
-
Call
signOut:
.Call
signOut:
in your logout handler to remove a user's authorization data (access tokens, profile) from the local store, and their authentication state from the server. The input parameter tosignOut
is anAMZNAuthorizationRequestHandler
block object. The block should detect and handleNSError
objects, which are returned whensignOut:
fails.[[AMZNAuthorizationManager sharedManager] signOut:^(NSError * _Nullable error) { if (!error) { // error from the SDK or Login with Amazon authorization server. } }];
Test your Integration
Launch your app in an iOS device or simulator and confirm you can log in with your Amazon.com credentials.
authorizeUserForScopes
request, or Unknown Error Code for an clearAuthorizationState request
. This is a known bug with Apple which occurs when the SDK tries to access the keychain. Until Apple resolves the bug, you can work around it by enabling Keychain Sharing for your app under the Capabilities tab of your app's target. This bug only impacts simulators. You can test on actual iOS10 devices without using any workaround.