簡體   English   中英

自動登錄子域 Amazon Cognito Identity

[英]Automatic login on subdomain Amazon Cognito Identity

我使用 Amazon Cognito Identity SDK for JavaScript 在 www.mydomain.com 上登錄我的用戶。

我想知道是否可以讓我的用戶自動登錄 store.mydomain.com

據我所知,Cognito 將登錄令牌和其他內容存儲在 localstorage 中並且無法從子域訪問?

默認情況下,AWS Cognito JS SDK 使用 LocalStorage 來存儲身份驗證令牌。 您可以更改此行為並使用 cookie 來存儲令牌。 然后您可以在設置 cookie 時使用您的父域名,並且您的所有子域都可以訪問此 cookie。

為此,您可以在創建CognitoUserPool對象時使用 JS SDK 中的CookieStorage 類

下面的 TypeScript 代碼片段

完整的實現可以在這里找到。 可以在此處查看正在運行的應用程序。

要對用戶進行身份驗證(在主域上,例如 example.com) -

signIn(email: string, password: string): Observable<any> {
    let userPool = new CognitoUserPool({
       UserPoolId: environment._USER_POOL_ID,
       ClientId: environment._CLIENT_ID,
       Storage: new CookieStorage({secure: false, domain: "example.com"}),
    });
    let authenticationDetails = new AuthenticationDetails({
      Username: email,
      Password: password,
    });

    let userData = {
        Username: email,
        Pool: userPool,
        Storage: new CookieStorage({secure: false, domain: "example.com"}),
    };
    let cognitoUser = new CognitoUser(userData);
    return Observable.create((observer: Observer<any>) => {
      cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: result => {
          observer.next(result);
          observer.complete();
        },
        onFailure: error => observer.error(error),
      });
    });
}

檢查用戶是否已通過身份驗證(在子域上,例如 sub.example.com)

isAuthenticated(): Observable<boolean> {
    let userPool = new CognitoUserPool({
       UserPoolId: environment._USER_POOL_ID,
       ClientId: environment._CLIENT_ID,
       Storage: new CookieStorage({secure: false, domain: "example.com"}),
    });
    let cognitoUser = userPool.getCurrentUser();
    if (cognitoUser != null) {
      return Observable.create((observer: Observer<boolean>) => {
        cognitoUser.getSession((error, session) => {
          if (error) {
            console.error(error);
            observer.next(false);
            observer.complete();
          }
          console.log(session, session.isValid(), session.isAuthenticated);
          observer.next(session.isValid());
          observer.complete();
        });
      })
}

適用於 JavaScript 的 Amazon Cognito Identity SDK 的令牌確實存儲在本地存儲中。 但是,如果您使用 Cognito Hosted UI 和下面鏈接的 Cognito Auth SDK,則可以管理 SSO。

有效的方式是,如果您將令牌存儲在域的本地存儲中,則可以登錄。 否則,您點擊我們的登錄終端節點,如果有針對它存儲的 cookie,您將在響應中獲得令牌,這些令牌將存儲在本地存儲中,並且可以使用 Amazon Cognito Identity SDK 訪問(因為它們存儲在同一位置) .

https://github.com/aws/amazon-cognito-auth-js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM