Hosted UI
Using Amazon Cognito Hosted UI
Amazon Cognito User Pools provides a customizable user experience via a web "Hosted UI". The Hosted UI provides an OAuth 2.0 flow that allows you to launch a web view (without embedding an SDK for Cognito or a social provider) via your application. The Hosted UI allows end-users to login and register directly to your user pool, through Facebook, Amazon, and Google, as well as through OpenID Connect (OIDC) and SAML identity providers. The Amplify CLI will setup and configure a Hosted UI for you when adding Authentication to your app. Learn More
Automated Setup with CLI
When configuring Authentication with the CLI, you can choose an identity provider (Google, Facebook or Login with Amazon) or use Cognito User Pools directly. When setting up the social providers, you will need the domain name that is generated by Cognito User Pools, as well as the credentials retrieved from the social providers website.
Run the following command in your project’s root folder:
1amplify add auth
Select Default configuration with Social Provider (Federation):
1Do you want to use the default authentication and security configuration?2 Default configuration3❯ Default configuration with Social Provider (Federation)4 Manual configuration5 I want to learn more.
You will be asked for the credentials from your social provider setup:
Set up your app in Facebook by following Facebook's App Development guide. Facebook will provide you an App ID and App Secret for your application which you will find in the app's Basic Settings; Take note of these.
When configuring your app, use the following settings (the domain will be generated in the next section):
- When setting up scenarios, choose Facebook Login
- Add your Cognito User Pools domain with the /oauth2/idpresponse:
https://<your-user-pool-domain>/oauth2/idpresponse
to:- Facebook Login > Settings > Valid OAuth Redirect URIs
- Platforms > Website > Site URL
After going through the flow, run the following command to deploy the configured resources to the cloud:
1amplify push
You will find a domain-name provisioned by the CLI for the hosted UI as an output in the terminal. You can also find that information anytime later using the amplify status
command.
Your Cognito User Pool domain is structured like so:
<unique_domain_prefix>-<env-name>.auth.<region>.amazoncognito.com
. Use this domain in the above steps when setting up your social provider.
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:
1{2 "IdentityManager": {3 ...4 },5 "CredentialsProvider": {6 ...7 },8 "CognitoUserPool": {9 ...10 },11 "Auth": {12 "Default": {13 "OAuth": {14 "WebDomain": "YOUR_AUTH_DOMAIN.auth.us-west-2.amazoncognito.com", // Do not include the https:// prefix15 "AppClientId": "YOUR_APP_CLIENT_ID",16 "SignInRedirectURI": "myapp://",17 "SignOutRedirectURI": "myapp://",18 "Scopes": ["openid", "email"]19 }20 }21 }22}
Note: The User Pool OIDC JWT token obtained from a successful sign-in will be federated into a configured Cognito Identity Pool. The SDK will automatically exchange this information with Cognito in order to retrieve temporary AWS credentials (Access Key ID and Secret Key).
Setup Cognito Hosted UI in your iOS App
-
Add
myapp://
to your app's URL schemes:Right-click Info.plist and then choose Open As > Source Code.
Add the following entry in URL scheme:
1<plist version="1.0">23 <dict>4 <!-- YOUR OTHER PLIST ENTRIES HERE -->56 <!-- ADD AN ENTRY TO CFBundleURLTypes for Cognito Auth -->7 <!-- IF YOU DO NOT HAVE CFBundleURLTypes, YOU CAN COPY THE WHOLE BLOCK BELOW -->8 <key>CFBundleURLTypes</key>9 <array>10 <dict>11 <key>CFBundleURLSchemes</key>12 <array>13 <string>myapp</string>14 </array>15 </dict>16 </array>1718 <!-- ... -->19 </dict>
Launching the Hosted UI
To launch the Hosted UI from from your application, you can use the showSignIn
API of AWSMobileClient.default()
:
1// Optionally override the scopes based on the usecase.2let hostedUIOptions = HostedUIOptions(scopes: ["openid", "email"])3
4// Present the Hosted UI sign in.5AWSMobileClient.default().showSignIn(6 navigationController: self.navigationController!,7 hostedUIOptions: hostedUIOptions8) { (userState, error) in9 if let error = error as? AWSMobileClientError {10 print(error.localizedDescription)11 }12 if let userState = userState {13 print("Status: \(userState.rawValue)")14 }15}
Optional: If your app deployment target is < iOS 11, add the following callback in your App Delegate's
application:open url
method. This callback is required, becauseSFSafariViewController
is used in < iOS 11 to integrate with the Hosted UI.
1func application(2 _ application: UIApplication,3 open url: URL,4 sourceApplication: String?,5 annotation: Any6) -> Bool {7 AWSMobileClient.default().handleAuthResponse(8 application,9 open: url,10 sourceApplication: sourceApplication,11 annotation: annotation12 )13 return true14}
Note: By default, the Hosted UI will show all login 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.
Directly Launching Facebook, Google, or SAML
You can by-pass the Cognito Hosted UI screen and navigate directly to and from a third provider authentication page. This allows you to login with a social provider configured in Cognito User Pools while not displaying Cognito's Hosted UI (e.g. showing a Login with Facebook button in your application).
1// Option to launch Google sign in directly2let hostedUIOptions = HostedUIOptions(scopes: ["openid", "email"], identityProvider: "Google")3// OR4// Option to launch Facebook sign in directly5let hostedUIOptions = HostedUIOptions(scopes: ["openid", "email"], identityProvider: "Facebook")6// OR7// Option to launch Apple sign in directly8let hostedUIOptions = HostedUIOptions(identityProvider: "SignInWithApple")9
10// Present the Hosted UI sign in.11AWSMobileClient.default().showSignIn(12 navigationController: self.navigationController!,13 hostedUIOptions: hostedUIOptions14) { (userState, error) in15 if let error = error as? AWSMobileClientError {16 print(error.localizedDescription)17 }18 if let userState = userState {19 print("Status: \(userState.rawValue)")20 }21}
Signing out via the Hosted UI
1// Setting invalidateTokens: true will make sure the tokens are invalidated2AWSMobileClient.default().signOut(3 options: SignOutOptions(invalidateTokens: true)4) { (error) in5 print("Error: \(error.debugDescription)")6}
If you want to sign out locally by just deleting tokens, you can call signOut
method:
1AWSMobileClient.default().signOut()
Set up Auth with Auth0
You can use AWSMobileClient
to use Auth0
as an OAuth 2.0
provider. You use Auth0
as an identity provider for a Cognito Federated Identity Pool. This will allow users authenticated via Auth0 to have access to your AWS resources. Learn how to integrate Auth0 with Cognito Federated Identity Pools
Configure your iOS App
-
To configure your application for hosted UI, you need to use HostedUI options. Update your
awsconfiguration.json
file to add a new configuration forAuth
. The configuration should look like this:1{2 "IdentityManager": {3 ...4 },5 "CredentialsProvider": {6 ...7 },8 "CognitoUserPool": {9 ...10 },11 "Auth": {12 "Default": {13 "OAuth": {14 "AppClientId": "YOUR_AUTH0_APP_CLIENT_ID",15 "WebDomain": "YOUR_AUTH0_DOMAIN.auth0.com", // Do not include the https:// prefix16 "TokenURI": "https://YOUR_AUTH0_DOMAIN.auth0.com/oauth/token",17 "SignInURI": "https://YOUR_AUTH0_DOMAIN.auth0.com/authorize",18 "SignInRedirectURI": "com.your.bundle.configured.in.auth0://YOUR_AUTH0_DOMAIN.auth0.com/ios/com.your.bundle/callback",19 "SignOutURI": "https://YOUR_AUTH0_DOMAIN.auth0.com/v2/logout",20 "SignOutURIQueryParameters": {21 "client_id" : "YOUR_AUTH0_APP_CLIENT_ID",22 "returnTo" : "com.your.bundle.configured.in.auth0://yourserver.auth0.com/ios/com.amazonaws.AWSAuthSDKTestApp/callback"23 },24 "Scopes": ["openid", "email"]25 }26 }27 }28} -
Add the signin and signout redirect URIs to your app's URL schemes:
Right-click Info.plist and then choose Open As > Source Code.
Add the following entry in URL scheme:
1<plist version="1.0">23 <dict>4 <!-- YOUR OTHER PLIST ENTRIES HERE -->56 <!-- ADD AN ENTRY TO CFBundleURLTypes for Auth0 -->7 <!-- IF YOU DO NOT HAVE CFBundleURLTypes, YOU CAN COPY THE WHOLE BLOCK BELOW -->8 <key>CFBundleURLTypes</key>9 <array>10 <dict>11 <key>CFBundleURLSchemes</key>12 <array>13 <string>com.your.bundle.configured.in.auth0://yourserver.auth0.com/ios/com.amazonaws.AWSAuthSDKTestApp/callback</string>14 </array>15 </dict>16 </array>1718 <!-- ... -->19 </dict>
Launch the Hosted UI for Auth0
To launch the Hosted UI from from your application, you can use the showSignIn
API of AWSMobileClient.default()
:
1// Specify the scopes and federation provider name.2 let hostedUIOptions = HostedUIOptions(3 scopes: ["openid", "email"],4 federationProviderName: "YOUR_AUTH0_DOMAIN.auth0.com"5)6
7// Present the Hosted UI sign in.8AWSMobileClient.default().showSignIn(9 navigationController: self.navigationController!,10 hostedUIOptions: hostedUIOptions11) { (userState, error) in12 if let error = error as? AWSMobileClientError {13 print(error.localizedDescription)14 }15 if let userState = userState {16 print("Status: \(userState.rawValue)")17 }18}19
20// Present the Hosted UI sign in.21AWSMobileClient.default().showSignIn(22 navigationController: self.navigationController!,23 hostedUIOptions: hostedUIOptions24) { (userState, error) in25 if let error = error as? AWSMobileClientError {26 print(error.localizedDescription)27 }28 if let userState = userState {29 print("Status: \(userState.rawValue)")30 }31}
Optional: If your app deployment target is < iOS 11, add the following callback in your App Delegate's
application:open url
method. This callback is required, becauseSFSafariViewController
is used in < iOS 11 to integrate with the Hosted UI.
1func application(2 _ application: UIApplication,3 open url: URL,4 sourceApplication: String?,5 annotation: Any6) -> Bool {7 return AWSMobileClient.default().handleAuthResponse(8 application,9 open: url,10 sourceApplication: sourceApplication,11 annotation: annotation12 )13}
Signing Out via the Hosted UI
1// Setting invalidateTokens: true will make sure the tokens are invalidated2AWSMobileClient.default().signOut(3 options: SignOutOptions(invalidateTokens: true)4) { (error) in5 print("Error: \(error.debugDescription)")6}
If you want to sign out locally by just deleting tokens, you can call signOut
method:
1AWSMobileClient.default().signOut()