Cognito hosted UI

前端 未结 4 1694
盖世英雄少女心
盖世英雄少女心 2020-12-07 17:31

I have been looking into setting up a login for a web app that lets clients view data hosted in S3 and found that AWS Cognito has a hosted web UI [link] that handles most of

4条回答
  •  时光取名叫无心
    2020-12-07 18:23

    I implemented this flow, not using Amplify, just using Cognito Hosted UI:

    1. User navigates in my website (tab 1), and in any page user clicks the login/register button.
    2. A new tab(Tab 2) is open with the cognito hosted UI using my own domain (auth.example.com)
    3. Then user makes their business on hosted ui (login/new account/recover password,etc)
    4. Cognito send a HASH in the URL (with many tokens) to my site callback.(https://example.com/login )
    5. My site process the tokens: The trick is to create an Auth instance, this one can parse the hash and create the user on the LocalStorage:

      // mysite.com/login 
      import {CognitoAuth} from 'amazon-cognito-auth-js';
      
      // Configuration for Auth instance.
      var authData = {
          UserPoolId: 'us-east-1_xxxx',
          ClientId: '1vxxxxx',
          RedirectUriSignIn : 'https://example.com/login',
          RedirectUriSignOut : 'https://example.com/logout',
          AppWebDomain : 'example.com',
          TokenScopesArray: ['email']
          };
      var auth = new CognitoAuth(authData);
      
      //Callbacks, you must declare, but can be empty. 
      auth.userhandler = {
          onSuccess: function(result) {
      
          },
          onFailure: function(err) {
          }
      };
      
      //Get the full url with the hash data.
      var curUrl = window.location.href;
      
      
      //here is the trick, this step configure the LocalStorage with the user.
      auth.parseCognitoWebResponse(curUrl);
      window.top.close();
      
    6. After the user has been set in the Local Storage, the callback(tab 2) is closed.

    7. On my site (tab 1) I configure an EventListener to listen if there is a change in the Local Storage.

            constructor() {
            window.addEventListener('storage', this.userLogged);
            }
      
            userLogged(event) {
      
              if (event.key.indexOf('CognitoIdentityServiceProvider') !== -1) {
      
                var data = {
                            UserPoolId: 'us-east-1_xxxxx',
                            ClientId: 'xxxxx'
                            };
      
               var userPool = new CognitoUserPool(data);
      
               //behind the scene getCurrentUser looks for the user on the local storage. 
               var cognitoUser = userPool.getCurrentUser();
                  }
             }
      
    8. With cognitoUser you are done, because you can retrieve credentials or other data.

提交回复
热议问题