

The AWS SDK for JavaScript v2 has reached end-of-support. We recommend that you migrate to [AWS SDK for JavaScript v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/).

# Setting Credentials
<a name="setting-credentials"></a>

AWS uses credentials to identify who is calling services and whether access to the requested resources is allowed. 

Whether running in a web browser or in a Node.js server, your JavaScript code must obtain valid credentials before it can access services through the API. Credentials can be set globally on the configuration object, using `AWS.Config`, or per service, by passing credentials directly to a service object.

There are several ways to set credentials that differ between Node.js and JavaScript in web browsers. The topics in this section describe how to set credentials in Node.js or web browsers. In each case, the options are presented in recommended order.

## Best Practices for Credentials
<a name="credentials-best-practices"></a>

Properly setting credentials ensures that your application or browser script can access the services and resources needed while minimizing exposure to security issues that may impact mission critical applications or compromise sensitive data.

An important principle to apply when setting credentials is to always grant the least privilege required for your task. It's more secure to provide minimal permissions on your resources and add further permissions as needed, rather than provide permissions that exceed the least privilege and, as a result, be required to fix security issues you might discover later. For example, unless you have a need to read and write individual resources, such as objects in an Amazon S3 bucket or a DynamoDB table, set those permissions to read only.

For more information on granting the least privilege, see the [Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege) section of the Best Practices topic in the * IAM User Guide*.

**Warning**  
While it is possible to do so, we recommend you not hard code credentials inside an application or browser script. Hard coding credentials poses a risk of exposing sensitive information.

For more information about how to manage your access keys, see [ Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) in the AWS General Reference.

**Topics**
+ [Best Practices for Credentials](#credentials-best-practices)
+ [Setting Credentials in Node.js](setting-credentials-node.md)
+ [Setting Credentials in a Web Browser](setting-credentials-browser.md)

# Setting Credentials in Node.js
<a name="setting-credentials-node"></a>

There are several ways in Node.js to supply your credentials to the SDK. Some of these are more secure and others afford greater convenience while developing an application. When obtaining credentials in Node.js, be careful about relying on more than one source such as an environment variable and a JSON file you load. You can change the permissions under which your code runs without realizing the change has happened.

Here are the ways you can supply your credentials in order of recommendation:

1. Loaded from AWS Identity and Access Management (IAM) roles for Amazon EC2

1. Loaded from the shared credentials file (`~/.aws/credentials`)

1. Loaded from environment variables

1. Loaded from a JSON file on disk

1. Other credential-provider classes provided by the JavaScript SDK

If more than one credential source is available to the SDK, the default precedence of selection is as follows:

1. Credentials that are explicitly set through the service-client constructor

1. Environment variables

1. The shared credentials file

1. Credentials loaded from the ECS credentials provider (if applicable)

1. Credentials that are obtained by using a credential process specified in the shared AWS config file or the shared credentials file. For more information, see [Loading Credentials in Node.js using a Configured Credential Process](loading-node-credentials-configured-credential-process.md).

1. Credentials loaded from AWS IAM using the credentials provider of the Amazon EC2 instance (if configured in the instance metadata)

For more information, see [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) and [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CredentialProviderChain.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CredentialProviderChain.html) in the API reference.

**Warning**  
While it is possible to do so, we do not recommend hard-coding your AWS credentials in your application. Hard-coding credentials poses a risk of exposing your access key ID and secret access key.

The topics in this section describe how to load credentials into Node.js.

**Topics**
+ [Loading Credentials in Node.js from IAM roles for Amazon EC2](loading-node-credentials-iam.md)
+ [Loading Credentials for a Node.js Lambda Function](loading-node-credentials-lambda.md)
+ [Loading Credentials in Node.js from the Shared Credentials File](loading-node-credentials-shared.md)
+ [Loading Credentials in Node.js from Environment Variables](loading-node-credentials-environment.md)
+ [Loading Credentials in Node.js from a JSON File](loading-node-credentials-json-file.md)
+ [Loading Credentials in Node.js using a Configured Credential Process](loading-node-credentials-configured-credential-process.md)

# Loading Credentials in Node.js from IAM roles for Amazon EC2
<a name="loading-node-credentials-iam"></a>

If you run your Node.js application on an Amazon EC2 instance, you can leverage IAM roles for Amazon EC2 to automatically provide credentials to the instance. If you configure your instance to use IAM roles, the SDK automatically selects the IAM credentials for your application, eliminating the need to manually provide credentials.

For more information on adding IAM roles to an Amazon EC2 instance, see [Using IAM roles for Amazon EC2 instances](https://docs.aws.amazon.com/sdkref/latest/guide/access-iam-roles-for-ec2.html) in the *AWS SDKs and Tools Reference Guide*.

# Loading Credentials for a Node.js Lambda Function
<a name="loading-node-credentials-lambda"></a>

When you create an AWS Lambda function, you must create a special IAM role that has permission to execute the function. This role is called the *execution role*. When you set up a Lambda function, you must specify the IAM role you created as the corresponding execution role.

The execution role provides the Lambda function with the credentials it needs to run and to invoke other web services. As a result, you do not need to provide credentials to the Node.js code you write within a Lambda function.

For more information about creating a Lambda execution role, see [Manage Permissions: Using an IAM Role (Execution Role)](https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role) in the *AWS Lambda Developer Guide*.

# Loading Credentials in Node.js from the Shared Credentials File
<a name="loading-node-credentials-shared"></a>

You can keep your AWS credentials data in a shared file used by SDKs and the command line interface. When the SDK for JavaScript loads, it automatically searches the shared credentials file, which is named "credentials". Where you keep the shared credentials file depends on your operating system:
+ The shared credentials file on Linux, Unix, and macOS: `~/.aws/credentials`
+ The shared credentials file on Windows: `C:\Users\USER_NAME\.aws\credentials`

If you do not already have a shared credentials file, see [SDK authentication with AWS](getting-your-credentials.md). Once you follow those instructions, you should see text similar to the following in the credentials file, where *<YOUR\$1ACCESS\$1KEY\$1ID>* is your access key ID and *<YOUR\$1SECRET\$1ACCESS\$1KEY>* is your secret access key:

```
[default]
aws_access_key_id = <YOUR_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>
```

For an example showing this file being used, see [Getting Started in Node.js](getting-started-nodejs.md).

The `[default]` section heading specifies a default profile and associated values for credentials. You can create additional profiles in the same shared configuration file, each with its own credential information. The following example shows a configuration file with the default profile and two additional profiles:

```
[default] ; default profile
aws_access_key_id = <DEFAULT_ACCESS_KEY_ID>
aws_secret_access_key = <DEFAULT_SECRET_ACCESS_KEY>
    
[personal-account] ; personal account profile
aws_access_key_id = <PERSONAL_ACCESS_KEY_ID>
aws_secret_access_key = <PERSONAL_SECRET_ACCESS_KEY>
    
[work-account] ; work account profile
aws_access_key_id = <WORK_ACCESS_KEY_ID>
aws_secret_access_key = <WORK_SECRET_ACCESS_KEY>
```

By default, the SDK checks the `AWS_PROFILE` environment variable to determine which profile to use. If the `AWS_PROFILE` variable is not set in your environment, the SDK uses the credentials for the `[default]` profile. To use one of the alternate profiles, set or change the value of the `AWS_PROFILE` environment variable. For example, given the configuration file shown above, to use the credentials from the work account, set the `AWS_PROFILE` environment variable to `work-account` (as appropriate for your operating system).

**Note**  
When setting environment variables, be sure to take appropriate actions afterwards (according to the needs of your operating system) to make the variables available in the shell or command environment.

After setting the environment variable (if needed), you can run a JavaScript file that uses the SDK, such as for example, a file named `script.js`.

```
$ node script.js
```

You can also explicitly select the profile used by the SDK, either by setting `process.env.AWS_PROFILE` before loading the SDK, or by selecting the credential provider as shown in the following example:

```
var credentials = new AWS.SharedIniFileCredentials({profile: 'work-account'});
AWS.config.credentials = credentials;
```

# Loading Credentials in Node.js from Environment Variables
<a name="loading-node-credentials-environment"></a>

The SDK automatically detects AWS credentials set as variables in your environment and uses them for SDK requests, eliminating the need to manage credentials in your application. The environment variables that you set to provide your credentials are:
+ `AWS_ACCESS_KEY_ID`
+ `AWS_SECRET_ACCESS_KEY`
+ `AWS_SESSION_TOKEN`

For more details on setting environment variables, see [Environment variables support](https://docs.aws.amazon.com/sdkref/latest/guide/environment-variables.html) in the *AWS SDKs and Tools Reference Guide*.

# Loading Credentials in Node.js from a JSON File
<a name="loading-node-credentials-json-file"></a>

You can load configuration and credentials from a JSON document on disk using `AWS.config.loadFromPath`. The path specified is relative to the current working directory of your process. For example, to load credentials from a `'config.json'` file with the following content:

```
{ "accessKeyId": <YOUR_ACCESS_KEY_ID>, "secretAccessKey": <YOUR_SECRET_ACCESS_KEY>, "region": "us-east-1" }
```

Then use the following code:

```
var AWS = require("aws-sdk");
AWS.config.loadFromPath('./config.json');
```

**Note**  
Loading configuration data from a JSON document resets all existing configuration data. Add additional configuration data after using this technique. Loading credentials from a JSON document is not supported in browser scripts.

# Loading Credentials in Node.js using a Configured Credential Process
<a name="loading-node-credentials-configured-credential-process"></a>

You can source credentials by using a method that isn't built into the SDK. To do this, specify a credential process in the shared AWS conﬁg file or the shared credentials file. If the `AWS_SDK_LOAD_CONFIG` environment variable is set to any value, the SDK will prefer the process specified in the config file over the process specified in the credentials file (if any).

For details about specifying a credential process in the shared AWS config file or the shared credentials file, see the *AWS CLI Command Reference*, specifically the information about [Sourcing Credentials From External Processes](https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#sourcing-credentials-from-external-processes).

For information about using the `AWS_SDK_LOAD_CONFIG` environment variable, see [Using a Shared Config File](setting-region.md#setting-region-config-file) in this document.

# Setting Credentials in a Web Browser
<a name="setting-credentials-browser"></a>

There are several ways to supply your credentials to the SDK from browser scripts. Some of these are more secure and others afford greater convenience while developing a script. Here are the ways you can supply your credentials in order of recommendation:

1. Using Amazon Cognito Identity to authenticate users and supply credentials

1. Using web federated identity

1. Hard coded in the script

**Warning**  
We do not recommend hard coding your AWS credentials in your scripts. Hard coding credentials poses a risk of exposing your access key ID and secret access key.

**Topics**
+ [Using Amazon Cognito Identity to Authenticate Users](loading-browser-credentials-cognito.md)
+ [Using Web Federated Identity to Authenticate Users](loading-browser-credentials-federated-id.md)
+ [Web Federated Identity Examples](config-web-identity-examples.md)

# Using Amazon Cognito Identity to Authenticate Users
<a name="loading-browser-credentials-cognito"></a>

The recommended way to obtain AWS credentials for your browser scripts is to use the Amazon Cognito Identity credentials object, `AWS.CognitoIdentityCredentials`. Amazon Cognito enables authentication of users through third-party identity providers.

To use Amazon Cognito Identity, you must first create an identity pool in the Amazon Cognito console. An identity pool represents the group of identities that your application provides to your users. The identities given to users uniquely identify each user account. Amazon Cognito identities are not credentials. They are exchanged for credentials using web identity federation support in AWS Security Token Service (AWS STS).

Amazon Cognito helps you manage the abstraction of identities across multiple identity providers with the `AWS.CognitoIdentityCredentials` object. The identity that is loaded is then exchanged for credentials in AWS STS.

## Configuring the Amazon Cognito Identity Credentials Object
<a name="browser-cognito-configuration"></a>

If you have not yet created one, create an identity pool to use with your browser scripts in the [Amazon Cognito console](https://console.aws.amazon.com/cognito) before you configure `AWS.CognitoIdentityCredentials`. Create and associate both authenticated and unauthenticated IAM roles for your identity pool.

Unauthenticated users do not have their identity verified, making this role appropriate for guest users of your app or in cases when it doesn't matter if users have their identities verified. Authenticated users log in to your application through a third-party identity provider that verifies their identities. Make sure you scope the permissions of resources appropriately so you don't grant access to them from unauthenticated users.

After you configure an identity pool with identity providers attached, you can use `AWS.CognitoIdentityCredentials` to authenticate users. To configure your application credentials to use `AWS.CognitoIdentityCredentials`, set the `credentials` property of either `AWS.Config` or a per-service configuration. The following example uses `AWS.Config`:

```
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030',
  Logins: { // optional tokens, used for authenticated login
    'graph.facebook.com': 'FBTOKEN',
    'www.amazon.com': 'AMAZONTOKEN',
    'accounts.google.com': 'GOOGLETOKEN'
  }
});
```

The optional `Logins` property is a map of identity provider names to the identity tokens for those providers. How you get the token from your identity provider depends on the provider you use. For example, if Facebook is one of your identity providers, you might use the `FB.login` function from the [Facebook SDK](https://developers.facebook.com/docs/facebook-login/web) to get an identity provider token:

```
FB.login(function (response) {
  if (response.authResponse) { // logged in
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030',
      Logins: {
        'graph.facebook.com': response.authResponse.accessToken
      }
    });

    s3 = new AWS.S3; // we can now create our service object

    console.log('You are now logged in.');
  } else {
    console.log('There was a problem logging you in.');
  }
});
```

## Switching Unauthenticated Users to Authenticated Users
<a name="browser-switching-unauthenticated-users"></a>

Amazon Cognito supports both authenticated and unauthenticated users. Unauthenticated users receive access to your resources even if they aren't logged in with any of your identity providers. This degree of access is useful to display content to users prior to logging in. Each unauthenticated user has a unique identity in Amazon Cognito even though they have not been individually logged in and authenticated.

### Initially Unauthenticated User
<a name="browser-switching-initially-unauthenticated-user"></a>

Users typically start with the unauthenticated role, for which you set the credentials property of your configuration object without a `Logins` property. In this case, your default configuration might look like the following:

```
// set the default config object
var creds = new AWS.CognitoIdentityCredentials({
 IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030'
});
AWS.config.credentials = creds;
```

### Switch to Authenticated User
<a name="switch-to-authenticated"></a>

When an unauthenticated user logs in to an identity provider and you have a token, you can switch the user from unauthenticated to authenticated by calling a custom function that updates the credentials object and adds the `Logins` token:

```
// Called when an identity provider has a token for a logged in user
function userLoggedIn(providerName, token) {
  creds.params.Logins = creds.params.Logins || {};
  creds.params.Logins[providerName] = token;
                    
  // Expire credentials to refresh them on the next request
  creds.expired = true;
}
```

You can also Create `CognitoIdentityCredentials` object. If you do, you must reset the credentials properties of existing service objects you created. Service objects read from the global configuration only on object initialization. 

For more information about the `CognitoIdentityCredentials` object, see [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityCredentials.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityCredentials.html) in the AWS SDK for JavaScript API Reference. 

# Using Web Federated Identity to Authenticate Users
<a name="loading-browser-credentials-federated-id"></a>

You can directly configure individual identity providers to access AWS resources using web identity federation. AWS currently supports authenticating users using web identity federation through several identity providers:
+ [Login with Amazon](https://login.amazon.com)
+ [Facebook Login](https://www.facebook.com/about/login)
+ [Google Sign-in](https://developers.google.com/identity/)

You must first register your application with the providers that your application supports. Next, create an IAM role and set up permissions for it. The IAM role you create is then used to grant the permissions you configured for it through the respective identity provider. For example, you can set up a role that allows users who logged in through Facebook to have read access to a specific Amazon S3 bucket you control.

After you have both an IAM role with configured privileges and an application registered with your chosen identity providers, you can set up the SDK to get credentials for the IAM role using helper code, as follows:

```
AWS.config.credentials = new AWS.WebIdentityCredentials({
   RoleArn: 'arn:aws:iam::<AWS_ACCOUNT_ID>/:role/<WEB_IDENTITY_ROLE_NAME>',
   ProviderId: 'graph.facebook.com|www.amazon.com', // this is null for Google
   WebIdentityToken: ACCESS_TOKEN
});
```

The value in the `ProviderId` parameter depends on the specified identity provider. The value in the `WebIdentityToken` parameter is the access token retrieved from a successful login with the identity provider. For more information on how to configure and retrieve access tokens for each identity provider, see the documentation for the identity provider.

## Step 1: Registering with Identity Providers
<a name="config-web-identity-register"></a>

To begin, register an application with the identity providers you choose to support. You will be asked to provide information that identifies your application and possibly its author. This ensures that the identity providers know who is receiving their user information. In each case, the identity provider will issue an application ID that you use to configure user roles.

## Step 2: Creating an IAM Role for an Identity Provider
<a name="config-web-identity-role"></a>

After you obtain the application ID from an identity provider, go to the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) to create a new IAM role.

**To create an IAM role for an identity provider**

1. Go to the **Roles** section of the console and then choose **Create New Role**.

1. Type a name for the new role that helps you keep track of its use, such as **facebookIdentity**, and then choose **Next Step**.

1. In **Select Role Type**, choose **Role for Identity Provider Access**.

1. For **Grant access to web identity providers**, choose **Select**.

1. From the **Identity Provider** list, choose the identity provider that you want to use for this IAM role.  
![\[Selecting Role for Identity Provider Access\]](http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/images/iam-provider-select.png)

1. Type the application ID provided by the identity provider in **Application ID** and then choose **Next Step**.

1. Configure permissions for the resources you want to expose, allowing access to specific operations on specific resources. For more information about IAM permissions, see [ Overview of AWS IAM Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_permissions.html) in the *IAM User Guide*. Review and, if needed, customize the role's trust relationship, and then choose **Next Step**.

1. Attach additional policies you need and then choose **Next Step**. For more information about IAM policies, see [Overview of IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) in the *IAM User Guide*.

1. Review the new role and then choose **Create Role**.

You can provide other constraints to the role, such as scoping it to specific user IDs. If the role grants write permissions to your resources, make sure you correctly scope the role to users with the correct privileges, otherwise any user with an Amazon, Facebook, or Google identity will be able to modify resources in your application.

For more information on using web identity federation in IAM, see [ About Web Identity Federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html) in the *IAM User Guide*.

## Step 3: Obtaining a Provider Access Token After Login
<a name="config-web-identity-obtain-token"></a>

Set up the login action for your application by using the identity provider's SDK. You can download and install a JavaScript SDK from the identity provider that enables user login, using either OAuth or OpenID. For information on how to download and set up the SDK code in your application, see the SDK documentation for your identity provider:
+ [Login with Amazon](https://login.amazon.com/website)
+ [Facebook Login](https://developers.facebook.com/docs/javascript)
+ [Google Sign-in](https://developers.google.com/identity/)

## Step 4: Obtaining Temporary Credentials
<a name="config-web-identity-get-credentials"></a>

After your application, roles, and resource permissions are configured, add the code to your application to obtain temporary credentials. These credentials are provided through the AWS Security Token Service using web identity federation. Users log in to the identity provider, which returns an access token. Set up the `AWS.WebIdentityCredentials` object using the ARN for the IAM role you created for this identity provider:

```
AWS.config.credentials = new AWS.WebIdentityCredentials({
    RoleArn: 'arn:aws:iam::<AWS_ACCOUNT_ID>:role/<WEB_IDENTITY_ROLE_NAME>',
    ProviderId: 'graph.facebook.com|www.amazon.com', // Omit this for Google
    WebIdentityToken: ACCESS_TOKEN // Access token from identity provider
});
```

Service objects that are created subsequently will have the proper credentials. Objects created before setting the `AWS.config.credentials` property won't have the current credentials.

You can also create `AWS.WebIdentityCredentials` before retrieving the access token. This allows you to create service objects that depend on credentials before loading the access token. To do this, create the credentials object without the `WebIdentityToken` parameter:

```
AWS.config.credentials = new AWS.WebIdentityCredentials({
  RoleArn: 'arn:aws:iam::<AWS_ACCOUNT_ID>:role/<WEB_IDENTITY_ROLE_NAME>',
  ProviderId: 'graph.facebook.com|www.amazon.com' // Omit this for Google
});

// Create a service object
var s3 = new AWS.S3;
```

Then set `WebIdentityToken` in the callback from the identity provider SDK that contains the access token:

```
AWS.config.credentials.params.WebIdentityToken = accessToken;
```

# Web Federated Identity Examples
<a name="config-web-identity-examples"></a>

Here are a few examples of using web federated identity to obtain credentials in browser JavaScript. These examples must be run from an http:// or https:// host scheme to ensure the identity provider can redirect to your application. 

## Login with Amazon Example
<a name="config-web-identity-amazon-login-example"></a>

The following code shows how to use Login with Amazon as an identity provider. 

```
<a href="#" id="login">
  <img border="0" alt="Login with Amazon"
    src="https://images-na.ssl-images-amazon.com/images/G/01/lwa/btnLWA_gold_156x32.png"
    width="156" height="32" />
</a>
<div id="amazon-root"></div>
<script type="text/javascript">
  var s3 = null;
  var clientId = 'amzn1.application-oa2-client.1234567890abcdef'; // client ID
  var roleArn = 'arn:aws:iam::<AWS_ACCOUNT_ID>:role/<WEB_IDENTITY_ROLE_NAME>';

  window.onAmazonLoginReady = function() {
    amazon.Login.setClientId(clientId); // set client ID

    document.getElementById('login').onclick = function() {
      amazon.Login.authorize({scope: 'profile'}, function(response) {
        if (!response.error) { // logged in
          AWS.config.credentials = new AWS.WebIdentityCredentials({
            RoleArn: roleArn,
            ProviderId: 'www.amazon.com',
            WebIdentityToken: response.access_token
          });

          s3 = new AWS.S3();

          console.log('You are now logged in.');
        } else {
          console.log('There was a problem logging you in.');
        }
      });
    };
  };

  (function(d) {
    var a = d.createElement('script'); a.type = 'text/javascript';
    a.async = true; a.id = 'amazon-login-sdk';
    a.src = 'https://api-cdn.amazon.com/sdk/login1.js';
    d.getElementById('amazon-root').appendChild(a);
  })(document);
</script>
```

## Facebook Login Example
<a name="config-web-identity-facebook-login-example"></a>

The following code shows how to use Facebook Login as an identity provider:

```
<button id="login">Login</button>
<div id="fb-root"></div>
<script type="text/javascript">
var s3 = null;
var appId = '1234567890'; // Facebook app ID
var roleArn = 'arn:aws:iam::<AWS_ACCOUNT_ID>:role/<WEB_IDENTITY_ROLE_NAME>';

window.fbAsyncInit = function() {
  // init the FB JS SDK
  FB.init({appId: appId});

  document.getElementById('login').onclick = function() {
    FB.login(function (response) {
      if (response.authResponse) { // logged in
        AWS.config.credentials = new AWS.WebIdentityCredentials({
          RoleArn: roleArn,
          ProviderId: 'graph.facebook.com',
          WebIdentityToken: response.authResponse.accessToken
        });

        s3 = new AWS.S3;

        console.log('You are now logged in.');
      } else {
        console.log('There was a problem logging you in.');
      }
    });
  };
};

// Load the FB JS SDK asynchronously
(function(d, s, id){
   var js, fjs = d.getElementsByTagName(s)[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement(s); js.id = id;
   js.src = "//connect.facebook.net/en_US/all.js";
   fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));
</script>
```

## Google\$1 Sign-in Example
<a name="config-web-identity-google-login-example"></a>

The following code shows how to use Google\$1 Sign-in as an identity provider. The access token used for web identity federation from Google is stored in `response.id_token` instead of `access_token` like other identity providers. 

```
<span
  id="login"
  class="g-signin"
  data-height="short"
  data-callback="loginToGoogle"
  data-cookiepolicy="single_host_origin"
  data-requestvisibleactions="http://schemas.google.com/AddActivity"
  data-scope="https://www.googleapis.com/auth/plus.login">
</span>
<script type="text/javascript">
  var s3 = null;
  var clientID = '1234567890.apps.googleusercontent.com'; // Google client ID
  var roleArn = 'arn:aws:iam::<AWS_ACCOUNT_ID>:role/<WEB_IDENTITY_ROLE_NAME>';

  document.getElementById('login').setAttribute('data-clientid', clientID);
  function loginToGoogle(response) {
    if (!response.error) {
      AWS.config.credentials = new AWS.WebIdentityCredentials({
        RoleArn: roleArn, WebIdentityToken: response.id_token
      });

      s3 = new AWS.S3();

      console.log('You are now logged in.');
    } else {
      console.log('There was a problem logging you in.');
    }
  }

  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/client:plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
 </script>
```