
## Amazon Cognito Hosted UI

Amazon Cognito provides a customizable user experience via the Hosted UI. The Hosted UI is an OAuth 2.0 flow that allows you to launch a login screen without embedding an SDK for Cognito or a social provider into your application. The Hosted UI allows end-users to sign-in directly to your user pool through Facebook, Amazon, and Google, as well as through OpenID Connect (OIDC) and SAML identity providers. To learn more about Amazon Cognito Hosted UI, please visit [Amazon Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html).

You need to configure your identity providers(Google, Facebook or Login with Amazon) which you would like to use.

import all0 from "/src/fragments/lib/auth/common/social_signin_web_ui/setup_auth_provider.mdx";

<Fragments fragments={{all: all0}} />

## Configure Auth Category
Once you have the social provider configured, run the following in your project’s root folder:

```bash
amplify add auth     ## "amplify update auth" if already configured
```

Choose the following options (the last steps are specific to Facebook here but are similar for other providers):

```console
? Do you want to use the default authentication and security configuration? 
    `Default configuration with Social Provider (Federation)`
? How do you want users to be able to sign in? 
    `Username`
? Do you want to configure advanced settings? 
    `No, I am done.`
? What domain name prefix you want us to create for you? 
    `(default)`
? Enter your redirect signin URI: 
    `http://localhost:3000/`
? Do you want to add another redirect signin URI 
    `No`
? Enter your redirect signout URI: 
    `http://localhost:3000/`
? Do you want to add another redirect signout URI 
    `No`
? Select the social providers you want to configure for your user pool: 
    `<choose your provider and follow the prompts to input the proper tokens>`
```


import all1 from "/src/fragments/lib/auth/common/social_signin_web_ui/configure_auth_category.mdx";

<Fragments fragments={{all: all1}} />

## Setup Amazon Cognito Hosted UI in Android App

<BlockSwitcher>
<Block name="Version 2.27.0 and above">

Add the following activity and queries tag to your app's `AndroidManifest.xml` file, replacing `myapp` with
whatever value you used for your redirect URI prefix:

```xml
<queries>
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
  </intent>
  <intent>
    <action android:name=
        "android.support.customtabs.action.CustomTabsService" />
  </intent>
</queries>
<application ...>
  ...
  <activity
      android:name="com.amazonaws.mobile.client.activities.HostedUIRedirectActivity"
      android:exported="true">
      <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="myapp" />
      </intent-filter>
  </activity>
  ...
</application>
```

</Block>
<Block name="Version 2.24.0 and above">

1. Add the following activity to your app's `AndroidManifest.xml` file, replacing `myapp` with
whatever value you used for your redirect URI prefix:

  ```xml
  <activity
      android:name="com.amazonaws.mobile.client.activities.HostedUIRedirectActivity">
      <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="myapp" />
      </intent-filter>
  </activity>
  ```

2. If you previously setup HostedUI for versions between 2.18.0 and 2.23.0, then the only required change is to replace `com.amazonaws.mobileconnectors.cognitoauth.activities.CustomTabsRedirectActivity` with the updated version (`com.amazonaws.mobile.client.activities.HostedUIRedirectActivity`). You are no longer required to call the method `AWSMobileClient#handleAuthResponse(Intent)` in your app.

</Block>
<Block name="Version 2.18.0 - 2.23.0">

**Note:** These versions have known issues with the sign-out flow. Please use the SDK versions 2.24.0 and above.

1. Add the following activity to your app's `AndroidManifest.xml` file, replacing `myapp` with
whatever value you used for your redirect URI prefix:

  ```xml
  <activity
      android:name="com.amazonaws.mobileconnectors.cognitoauth.activities.CustomTabsRedirectActivity">
      <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="myapp" />
      </intent-filter>
  </activity>
  ```

2. Add the following result handler to whichever `Activity` you are calling HostedUI from:

  ```java
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == AuthClient.CUSTOM_TABS_ACTIVITY_CODE) {
    	    AWSMobileClient.getInstance().handleAuthResponse(data);
      }
  }
  ```

3. If you previously setup HostedUI for version 2.17.1 or below, remove the intent filter
you previously added to your activity in the `AndroidManifest.xml` file with the URI scheme (e.g. `myapp`) as well as the `onResume()` or `onNewIntent()` handler method you previously added to your `Activity`.

</Block>
<Block name="Version 2.17.1 and below">

1. Add `myapp://` to your app's Intent filters located in `AndroidManifest.xml`. The `your.package.YourAuthIntentHandlingActivity` will be referenced in the next step.

    ```xml
    <?xml version="1.0" encoding="utf-8"?>
     <manifest xmlns:android="http://schemas.android.com/apk/res/android"
               xmlns:amazon="http://schemas.amazon.com/apk/res/android"
               package="com.amazonaws.mobile.client">

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

        <application>
            <activity android:name="your.package.YourAuthIntentHandlingActivity">
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />
                    <data android:scheme="myapp" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    ```

2. Attach an intent callback so that `AWSMobileClient` can handle the callback and confirm sign-in or sign-out. This should be in `your.package.YourAuthIntentHandlingActivity`.

    ```java
    @Override
    protected void onResume() {
        super.onResume();
        Intent activityIntent = getIntent();
        if (activityIntent.getData() != null &&
                "myapp".equals(activityIntent.getData().getScheme())) {
            AWSMobileClient.getInstance().handleAuthResponse(activityIntent);
        }
    }
    ```

</Block>
</BlockSwitcher>

### Launching the Hosted UI

To launch the Hosted UI from from your application, you can use the `showSignIn` API of `AWSMobileClient.getInstance()`:

```java
// No options are being specified, only the config will be used
HostedUIOptions hostedUIOptions = HostedUIOptions.builder()
        .scopes("openid", "email")
        .build();
SignInUIOptions signInUIOptions = SignInUIOptions.builder()
        .hostedUIOptions(hostedUIOptions)
        .build();
// 'this' refers to the current active Activity
AWSMobileClient.getInstance().showSignIn(this, signInUIOptions, new Callback<UserStateDetails>() {
    @Override
    public void onResult(UserStateDetails details) {
        Log.d(TAG, "onResult: " + details.getUserState());
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError: ", e);
    }
});
```

**Note:** By default, the Hosted UI will show all sign-in options; the username-password flow as well as any social providers which are configured. If you wish to bypass the extra sign-in screen showing all the provider options and launch your desired social provider login directly, you can set the `HostedUIOptions` as shown in the next section.

### Configuring Hosted UI to launch Facebook/ Google/ SAML sign in directly

```java
// For Google
HostedUIOptions hostedUIOptions = HostedUIOptions.builder()
    .scopes("openid", "email")
    .identityProvider("Google")
    .build();

// For Facebook
HostedUIOptions hostedUIOptions = HostedUIOptions.builder()
    .scopes("openid", "email")
    .identityProvider("Facebook")
    .build();

SignInUIOptions signInUIOptions = SignInUIOptions.builder()
    .hostedUIOptions(hostedUIOptions)
    .build();
// 'this' refers to the current active Activity
AWSMobileClient.getInstance().showSignIn(this, signInUIOptions, new Callback<UserStateDetails>() {
    @Override
    public void onResult(UserStateDetails details) {
        Log.d(TAG, "onResult: " + details.getUserState());
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError: ", e);
    }
});
```

### Sign Out from HostedUI

```java
AWSMobileClient.getInstance().signOut(SignOutOptions.builder().invalidateTokens(true).build(), new Callback<Void>() {
    @Override
    public void onResult(Void result) {
        Log.d(TAG, "onResult: ");
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError: ", e);
    }
});
```

If you want to sign out locally by just deleting tokens, you can call `signOut` method:

```java
AWSMobileClient.getInstance().signOut();
```

### Add Response handler

Add the result handler if you need to capture sign in cancellations that occurred before the user submitted credentials.

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

    if (requestCode == AuthClient.CUSTOM_TABS_ACTIVITY_CODE &&
        resultCode == Activity.RESULT_CANCELED) {
        // handle canceled sign in
    }
}
```

### Manual Setup

To configure your application for hosted UI, you need to use *HostedUI* options. Update your `awsconfiguration.json` file to add a new configuration for `Auth`. The configuration should look like this:

```json
{
    "IdentityManager": {
        ...
    },
    "CredentialsProvider": {
        ...
    },
    "CognitoUserPool": {
        ...
    },
    "Auth": {
        "Default": {
            "OAuth": {
                "WebDomain": "YOUR_AUTH_DOMAIN.auth.us-west-2.amazoncognito.com", // Do not include the https:// prefix
                "AppClientId": "YOUR_APP_CLIENT_ID",
                "SignInRedirectURI": "myapp://callback",
                "SignOutRedirectURI": "myapp://signout",
                "Scopes": ["openid", "email"]
            }
        }
    }
}
```

Note: The User Pool OIDC JWT token obtained from a successful sign-in will be federated into a configured Cognito Identity pool in the `awsconfiguration.json` and the SDK will automatically exchange this with Cognito Identity to also retrieve AWS credentials.

## Using Auth0 Hosted UI

You can use `AWSMobileClient` to use `Auth0` as `OAuth 2.0`  provider.
You can use `Auth0` as one of the providers of your Cognito Federated Identity Pool.
This will allow users authenticated via Auth0 have access to your AWS resources. Learn [how to integrate Auth0 with Cognito Federated Identity Pools](https://auth0.com/docs/integrations/integrating-auth0-amazon-cognito-mobile-apps)

### Setup Auth0 Hosted UI in Android App

### Setup Amazon Cognito Hosted UI in Android App

1. To configure your application for hosted UI, you need to use *HostedUI* options. Update your `awsconfiguration.json` file to add a new configuration for `Auth`. The configuration should look like this:

    ```json
    {
        "IdentityManager": {
            ...
        },
        "CredentialsProvider": {
            ...
        },
        "CognitoUserPool": {
            ...
        },
        "Auth": {
            "Default": {
                "OAuth": {
                    "AppClientId": "YOUR_AUTH0_APP_CLIENT_ID",
                    "TokenURI": "https://YOUR_AUTH0_DOMAIN.auth0.com/oauth/token",
                    "SignInURI": "https://YOUR_AUTH0_DOMAIN.auth0.com/authorize",
                    "SignInRedirectURI": "com.your.bundle.configured.in.auth0://YOUR_AUTH0_DOMAIN.auth0.com/android/com.your.bundle/callback",
                    "SignOutURI": "https://YOUR_AUTH0_DOMAIN.auth0.com/v2/logout",
                    "SignOutRedirectURI": "com.your.bundle.configured.in.auth0://yourserver.auth0.com/android/com.amazonaws.AWSAuthSDKTestApp/signout",
                    "SignOutURIQueryParameters": {
                        "client_id" : "YOUR_AUTH0_APP_CLIENT_ID",
                        "returnTo" : "com.your.bundle.configured.in.auth0://yourserver.auth0.com/android/com.amazonaws.AWSAuthSDKTestApp/signout"
                    },
                    "Scopes": ["openid", "email"]
                }
            }
        }
    }
    ```

1. Add the sign-in and sign-out redirect URIs to your app's Intent filters located in `AndroidManifest.xml`.

    ```xml
    <?xml version="1.0" encoding="utf-8"?>
     <manifest xmlns:android="http://schemas.android.com/apk/res/android"
               xmlns:amazon="http://schemas.amazon.com/apk/res/android"
               package="com.amazonaws.mobile.client">

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

        <application>
            <activity android:name="your.package.YourAuthIntentHandlingActivity">
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />

                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />

                    <data android:scheme="com.your.bundle.configured.in.auth0" />
                </intent-filter>
            </activity>
        </application>

    </manifest>
    ```

1. Attach an intent callback so that the AWSMobileClient can handle the callback and confirm sign-in or sign-out. This should be in `your.package.YourAuthIntentHandlingActivity`.

    ```java
    @Override
    protected void onResume() {
        super.onResume();
        Intent activityIntent = getIntent();
        if (activityIntent.getData() != null &&
                "com.your.bundle.configured.in.auth0".equals(activityIntent.getData().getScheme())) {
            AWSMobileClient.getInstance().handleAuthResponse(activityIntent);
        }
    }
    ```

### Launching the Hosted UI for Auth0

To launch the Hosted UI from from your application, you can use the `showSignIn` API of `AWSMobileClient.getInstance()`:

```java
final HostedUIOptions hostedUIOptions = HostedUIOptions.builder()
        .federationProviderName("YOUR_AUTH0_DOMAIN.auth0.com")
        .build();
final SignInUIOptions signInUIOptions = SignInUIOptions.builder()
        .hostedUIOptions(hostedUIOptions)
        .build();
// 'this' refers to the current active Activity
AWSMobileClient.getInstance().showSignIn(this, signInUIOptions, new Callback<UserStateDetails>() {
    @Override
    public void onResult(UserStateDetails result) {
        Log.d(TAG, "onResult: " + result.getUserState());
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError: ", e);
    }
});
```

### Sign Out from HostedUI

```java
AWSMobileClient.getInstance().signOut(SignOutOptions.builder().invalidateTokens(true).build(), new Callback<Void>() {
    @Override
    public void onResult(Void result) {
        Log.d(TAG, "onResult: ");
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "onError: ", e);
    }
});
```

If you want to sign out locally by just deleting tokens, you can call `signOut` method:

```java
AWSMobileClient.getInstance().signOut();
```
