Login with Amazon SDK for JavaScript Reference Guide
This is the Login with Amazon SDK for JavaScript Reference. This documents contains reference information for the Login with Amazon SDK for JavaScript, as well as information about how to load the SDK. Login with Amazon is a web service that enables Amazon customers to login to your web or mobile app using their Amazon credentials. After they have logged in, your app can access some information from their Amazon profile.
amazon.Login Methods
All of the functions in login.js
are found in the amazon.Login
namespace. These functions allow you to identify your client application, request an access token, and exchange an access token for customer profile
information.
- authorize
- getClientId
- logout
- retrieveToken
- retrieveProfile
- setClientId
- setSandboxMode
- setSiteDomain
- setUseCookie
authorize
AuthorizeRequest authorize(options, next);
Requests authorization according to options
then redirects or calls next
. Depending on the options
set, a popup window will open to allow the user to login, or the window will redirect to the login page. You must call setClientId
prior to calling authorize. You must call authorize
prior to calling retrieveProfile
or retrieveToken
.
This method returns an AuthorizeRequest
object. Call onComplete
on that object to register a callback function or redirect URI, similar to the next
parameter. After the request is complete, the object will contain properties detailing the response (such as an access token or authorization code).
Parameters:
options
- required - (Object
).
options
can contain the following properties:interactive - (String)
Specifies when to show a login screen to the user.auto
will attempt to use a cached token. If the cached token fails or does not exist, the user will be presented with a login screen.always
does not use the cached token and always presents a login screen.never
will used the cached token; if the token does not work, authorize will returninvalid_grant
. Defaults toauto
.popup - (Boolean) true
to use a popup window for login,false
to redirect the current browser window to the authorization dialog. Defaults totrue
. Iffalse
, the next parameter MUST be a redirect URL . Popup windows are not supported in native iOS apps.response_type - (String)
The grant type requested. Specifytoken
to request an Implicit Grant orcode
to request an Authorization Code grant.token
is no longer supported. All future clients must specifycode
. Defaults totoken
.scope
- required - (String
orArray[String]
) The access scope requested. Must beprofile
,profile:user_id
,postal_code
, or some combination.state - (String)
A state parameter. An opaque value used by the client to maintain state between this request and the response. The Login with Amazon authorization service will include this value when redirecting the user back to the client. It is also used to prevent cross-site request forgery. For more information see Cross-site Request Forgery.pkce - (Boolean)
Used to secure authorization code grants via Proof Key for Code Exchange (PKCE). Must be set to true for Browser-Based apps. When true,response_type
will automatically be set tocode
. If nocode_challenge
is specified, the SDK generates acode_verifier
andcode_challenge
.code_challenge
is used in the authorization request.code_verifier
is stored in a cookie and used in the token request byretrieveToken
API. Defaults to false. For more information, see the PKCE RFC.code_challenge - (String)
Optional. Specifies acode_challenge
to include in the authorization request when using PKCE. If none is provided, and pkce is set to true, the SDK generates acode_verifier
andcode_challenge
. If generating thecode_verifier
yourself, thecode_challenge
should be computed using SHA-256.
next
(Function
orString
) A URI to redirect the browser response, or a JavaScript function to call with the authorization response.
About the next
parameter
If next
is a URI, once the user logs in the current window will be redirected to the URI and the authorization response will be added to the query string. The URI must use the HTTPS protocol and belong to the same domain as the current window.
Example: Authorization Code Grant
options = { scope: 'profile', response_type: 'code' };
amazon.Login.authorize(options, 'https://example.org/redirect_here')
// on success the current window will redirect to:
// https://example.org/redirect_here?code=ABJHSCO...
// on failure the current window will redirect to:
// https://example.org/redirect_here?error=access_denied&…
Example: Implicit Grant (Deprecated)
options = { scope: 'profile' };
amazon.Login.authorize(options, 'https://example.org/redirect_here')
// on success the current window will redirect to:
// https://example.org/redirect_here?access_token=XYZ&token_type=bearer&…
// on failure the current window will redirect to:
// https://example.org/redirect_here?error=access_denied&…
If next
is a callback function, it will be invoked with a response object containing the fields of the authorization response.
Example: Authorization Code Grant
options = { scope: 'profile', response_type: 'code' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
alert('success: ' + response.code);
});
Example: Implicit Grant (Deprecated)
options = { scope: 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
alert('success: ' + response.access_token);
});
Response Caching
When authorize
receives a valid access token response, it automatically caches the token and associated metadata for reuse. This cache persists across page reloads and browser sessions. If a subsequent authorize
call can be fulfilled by the cached token response, the SDK will reuse that token instead of requesting a new authorization. Use options.interactive
to override this behavior.
Interactivity Modes
The options.interactive
setting allows you to choose between three interactivity modes. They are:
auto
: Attempt to authorize the user using the cached token. If that fails, initiate a new authorization, showing the login and consent screen if necessary.always
: Initiate a new authorization, showing the login screen and ignoring any cached token.never
: Attempt to authorize the user using the cached token. If that fails, return aninvalid_grant
error.
Returns
An AuthorizeRequest object. AuthorizeRequest allows callers to register a callback function or redirect URL to use when the login request is complete. It also allows callers to get the current status of the request. When the request is complete, new properties are added to AuthorizeRequest based on the type of authorization request. If the request fails, error properties are added to the object.
getClientID
getClientId();
Gets the client identifier
that will be used to request authorization. You must call setClientId
before calling this function.
Parameters
None.
Returns
clientId - (String)
. The client ID assigned to your application. Maximum size of 100 bytes.
See Also
logout
logout();
Logs out the current user after a call to authorize
.
Parameters
None.
Returns
None.
Examples:
<script type="text/javascript">
document.getElementById('logout').onclick = function() {
amazon.Login.logout();
};
</script>
See Also
retrieveToken
retrieveToken(code, callback);
For Browser-Based apps using PKCE (options.pkce = true
). Retrieves the access token and passes it to a callback function. Uses an authorization code provided by authorize
. If code and callback are not provided, returns the cached token if its valid or returns null
.
Uses the code_verifier
stored in the amazon_Login_pkce_params
cookie by authorize
API. Cookies must be enabled and the retrieveToken
call must be on the same domain as the authorize
call.
Parameters
code
- Optional - (String
) The authorization code
Callback (callback)
function(response);
Called with the token or an error string.
Callback Parameters
response - (Object)
success - (Boolean) true
if the request was successful, otherwisefalse
.error - (String)
Included if the request failed, and contains an error message.access_token - (String)
Included if the request was successful, and contains profile information.expires_in - (Number)
The number of seconds until the access token expires.
Example:
<script type="text/javascript">
window.doLogin = function() {
var tokenResponse = amazon.Login.retrieveToken();
if (tokenResponse) {
alert("Cached Access Token: " + tokenResponse.access_token);
} else {
options = {};
options.scope = 'profile';
options.pkce = true;
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
amazon.Login.retrieveToken(response.code, function(response) {
alert('Access Token: ' + response.access_token);
if (window.console && window.console.log)
window.console.log(response);
});
});
};
};
</script>
retrieveProfile
retrieveProfile(accessToken, callback);
Retrieves the customer profile and passes it to a callback function. Uses an access token provided by authorize
.
Parameters
accessToken
- Required - (String
) An access token.
Callback (callback)
function(response);
Called with the profile data or an error string.
Callback Parameters
response - (Object)
success - (Boolean) true
if the request was successful, otherwisefalse
.error - (String)
Included if the request failed, and contains an error message.profile - (Object)
Included if the request was successful, and contains profile information.CustomerId - (String)
An identifier that uniquely identifies the logged-in user for this caller. Only present if theprofile
orprofile:user_id
scopes are requested andgranted.Name - (String)
The customer's name. Only present if theprofile
scope is requested and granted.PostalCode - (String)
The postal code of the customer's primary address. Only present if thepostal_code
scope is requested and granted.PrimaryEmail - (String)
The primary email address for the customer. Only present if theprofile
scope is requested and granted.
Example 1:
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
setTimeout(window.doLogin, 1);
return false;
};
window.doLogin = function() {
options = {};
options.scope = 'profile';
options.pkce = true;
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
amazon.Login.retrieveToken(response.code, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
amazon.Login.retrieveProfile(response.access_token, function(response) {
alert('Hello, ' + response.profile.Name);
alert('Your e-mail address is ' + response.profile.PrimaryEmail);
alert('Your unique ID is ' + response.profile.CustomerId);
if (window.console && window.console.log)
window.console.log(response);
});
});
});
};
</script>
Example 2:
var access_token = 'Atza|EKdsnskdna…';
amazon.Login.retrieveProfile(access_token, function(response) {
if ( response.success ) {
alert('Hello, ' + response.profile.Name);
alert('Your e-mail address is ' + response.profile.PrimaryEmail);
alert('Your unique ID is ' + response.profile.CustomerId);
}
else {
alert('Oh no! An error happened: ' + response.error);
}
});
Example 3 (Deprecated):
If the access_token
is omitted, retrieveProfile
will call authorize
, requesting the profile
scope. This option is no longer supported.
amazon.Login.retrieveProfile(function (response) {
// Display profile information.
});
See Also
setClientId
setClientId(clientId);
Sets the client identifier that will be used to request authorization. You must call this function before calling authorize
.
Parameters
clientId
- Required - (String
). The client ID assigned to your application.
Returns
None.
Example:
window.onAmazonLoginReady = function() {
amazon.Login.setClientId('YOUR-CLIENT-ID');
};
setSandboxMode
setSandboxMode(sandboxMode);
Determines whether or not Login with Amazon should use the Amazon Pay sandbox for requests. To use the Amazon Pay sandbox, call setSandboxMode(true)
before calling authorize
.
Parameters
sandboxMode
- Required -(boolean)
.true
to use the Amazon Pay sandbox to process requests, otherwisefalse
.
Returns
None.
See Also
setSiteDomain
setSiteDomain(siteDomain);
Sets the domain to use for saving cookies.The domain must match the origin of the current page. Defaults to the full domain for the current page.For example, if you have two pages using the Login with Amazon SDK for JavaScript, site1.example.com
and site2.example.com
, you would set the site domain to example.com
in the header of each site. This will ensure that the cookies on both sites have access to the same cached tokens.
Parameters
siteDomain
- Required - (String
). The site to store Login with Amazon cookies. Must share the origin of the current page.
Returns
None.
See Also
setUseCookie
setUseCookie(useCookie);
Determines whether or not Login with Amazon should use access tokens written to the amazon_Login_accessToken
cookie. You can use this value to share an access token with another page. Access tokens will still only grant access to the registered account for whom they were created.
When true
, the Login with Amazon SDK for JavaScript will check this cookie for cached tokens, and store newly granted tokens in that cookie.
Parameters
useCookie
- Required - (boolean
).true
to store the access token from authorizein a cookie, otherwisefalse
.
Returns
None.
See Also
setRegion
setRegion(region);
Login With Amazon has multiple authorization and resource endpoints. This API determines the region
of the authorization and resource endpoints Login with Amazon SDK should talk to. This needs to be
called before the authorize
and retreiveProfile
APIs.
When not set, it defaults to “NorthAmerica”
Parameters
region
- (amazon.Login.Region
) - Required. It can be one of the following
- amazon.Login.Region.NorthAmerica
- amazon.Login.Region.Europe
- amazon.Login.Region.AsiaPacific
Returns
None.
amazon.Login Classes
AuthorizeRequest
The AuthorizeRequest
class is used in response to an authorize call. AuthorizeRequestM
allows callers to register a callback function or redirect URL to use when the login request is complete. It also allows callers to get the current status of the request. When the request is complete, AuthorizeRequest
adds new properties based on the type of authorization request. If the request fails, error properties provide information on the failure.
The following table details which properties are added for each response type:
Response Type | Properties |
---|---|
Authorization Response | code and state |
Access Token Response (Deprecated) | access_token, token_type, expires_in, and scope |
Error Response | error, error_description, and error_uri |
onComplete
onComplete(next);
Registers a callback function or sets a redirect URI to call when the authorization request is complete. If this function is called after the request is complete, the function or redirect will happen immediately. If a callback function is used, the AuthorizeRequest
will be the first parameter. If a redirect URI is used, the browser will redirect to that URI with the OAuth 2 response parameters included in the query string.
If multiple redirect URLs are set, AuthorizeRequest
uses the most recent one.
Parameters
next - (Function or String)
A URI to redirect the browser response, or a JavaScript function to call with the authorization response.
access_token
access_token - (String)
The access token issued by the authorization server.
code
code - (String)
An authorization code that can be exchanged for an access token.
error
error - (String)
A short error code indicating why the authorization failed. It can be one of the following:
Error | Description |
---|---|
access_denied | The customer or authorization server denied the request. |
invalid_grant | The authorization server denied the request due to inability to use a cached token. |
invalid_request | The request is missing a required parameter, has an invalid value, or is otherwise malformed. |
invalid_scope | One or more of the requested scopes are invalid. |
server_error | The authorization server encountered an unexpected error. This is analogous to a 500 HTTP status code. |
temporarily_unavailable | The authorization server is current unavailable due to a temporary condition. This is analogous to a 503 HTTP status code. |
unauthorized_client | The client is not authorized to perform this request. |
error_description
error_description - (String)
A human-readable description of the error.
error_uri
error_uri - (String)
A URI for a web page with more information on the error.
expires_in
expires_in - (Number)
The number of seconds until the access token expires.
scope
scope - (String)
The scope granted by the authorization server for the access token. Must be profile
, profile:user_id
, postal_code
, or some combination.
state
state - (String)
The state
value provided to authorize
using the options
object.
status
status - (String)
The current status of the request. One of queued
, in progress
, or complete
.
token_type
token_type - (String)
The type of token issued. Must be bearer.