Amplify v6 不将令牌从 Cognito 托管的 ui 返回到 Angular

问题描述 投票:0回答:1

我使用的是 Angular 15,并且已从 aws-amplify v5 更新到 v6。我必须重组一些调用,因为这是一个重大更改,并且我认为所有内容都已连接,但我的应用程序不再进行身份验证。我认为这与我的身份验证服务有关,因为这是它工作时的唯一变化。我目前正在使用 Cognito 托管 UI。

这是我目前的身份验证服务。

import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { Amplify } from 'aws-amplify';
import { environment } from 'src/environments/environment';
import { fetchAuthSession, getCurrentUser, signOut } from 'aws-amplify/auth';

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolId: environment.cognito.userPoolId,
      userPoolClientId: environment.cognito.appClientId,
      signUpVerificationMethod: 'code',
      loginWith: {
        oauth: {
          domain: 'my-app.auth.us-east-1.amazoncognito.com',
          scopes: [
            'email',
            'profile',
            'openid',
            'aws.cognito.signin.user.admin',
          ],
          redirectSignIn: [environment.redirectUrl],
          redirectSignOut: ['http://localhost:4200/'],
          responseType: 'code',
        },
      },
    },
  },
});
const currentConfig = Amplify.getConfig();
console.log('currentConfig', currentConfig);

@Injectable({ providedIn: 'root' })
export class AuthService {
  authIsLoading = new BehaviorSubject<boolean>(true);
  authDidFail = new BehaviorSubject<boolean>(false);
  authStatusChanged = new Subject<boolean>();
  public loggedIn = false;

  async getAuthenticatedUser() {
    try {
      const { username, userId, signInDetails } = await getCurrentUser();

      console.log(`The username: ${username}`);

      console.log(`The userId: ${userId}`);

      console.log(`The signInDetails: ${signInDetails}`);
      return signInDetails;
    } catch (err) {
      console.log(err);
      throw err;
    }
  }

  async getRefreshedAuthenticatedUser() {
    try {
      const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {};
      return { accessToken, idToken };
    } catch (err) {
      console.log(err);
      return null;
    }
  }

  async logout() {
    try {
      await signOut();
      this.authStatusChanged.next(false);
    } catch (error) {
      console.log(error);
    }
  }

  async isAuthenticated(): Promise<boolean> {
    const user = await this.getAuthenticatedUser();
    console.log('USERTIME', user);
    return !!user;
  }
}

此外,我还设置了 lambda preAuth 和 postAuth cognito 触发函数,以确保这些步骤发生并且都收到事件。所以它只是因为某种原因放大不给我我的令牌。另外,在我的 amplify v5 应用程序中,localStorage 也有这些令牌,但它们在 v6 中不存在

这是来自 Cognito 托管 UI 的 302 重定向

HTTP/2 302 
date: Mon, 20 Nov 2023 23:51:41 GMT
content-length: 0
location: http://localhost:4200/redirect/?code=0274cb71-2add-4bff-8f8f-9d004ea14438
content-security-policy-report-only: script-src https://d3oia8etllorh5.cloudfront.net https://my-view-app.auth.us-east-1.amazoncognito.com; style-src https://d3oia8etllorh5.cloudfront.net https://my-app.auth.us-east-1.amazoncognito.com; img-src https://placeholder.cloudfront.net https://my-app.auth.us-east-1.amazoncognito.com; report-uri https://my-app.auth.us-east-1.amazoncognito.com/cspreport
x-amz-cognito-request-id: dsfssd-ed22-4d41-a4cf-45add22e55fa
set-cookie: XSRF-TOKEN=""; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/; Secure; HttpOnly; SameSite=Lax
XSRF-TOKEN=2bf2bb29-e8b7-40ff-9914-7b41a7ac3d18; Path=/; Secure; HttpOnly; SameSite=Lax
cognito="H4sIAAAAAAAAAAH9AAL/XiELDZtKtGVzEjYV00NzW5p9zaydExOStPySiR1SBPOyKnEgsl4e53j3MTLptV8bCJo8elZBNSGu/jvy3TtJB70Z3sqYlrbUYp0u5C2y0pj5GMoRgzWGVCHdq1LRqeA1EwuVNaIcoJk1wvTm6ZUl20fK16XtrGg1VZ7eL1r+s/YOEi/43vO+NlGtFw6AHArhlhwDGRtEMDWY7PFCqfsTwIUnefTSCXbikC6gDgOn5Q+iOx8Ds9ZD5u4KI3Jj3Q4TiwbNLYTCAsdOyPEL25cJyLVueuQLV/fmUQ+U1LL58TyE8b0W2+kSY0/6UISpH5WyrOfsQUHhoUbauvZ+vCbUQgj9AAAA.H4sIAAAAAAAAAMtjLvQ8wJZutipCkXOd1e2P33qfWLqEXvth1xv8J7vc4yQAfSRTdSAAAAA=.4"; Version=1; Domain=my-app.auth.us-east-1.amazoncognito.com; Max-Age=3600; Expires=Tue, 21-Nov-2023 00:51:41 GMT; Path=/; Secure; HttpOnly; SameSite=Lax
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
strict-transport-security: max-age=31536000 ; includeSubDomains
x-frame-options: DENY
server: Server
X-Firefox-Spdy: h2

我看到的错误

ERROR Error: Uncaught (in promise): UserUnAuthenticatedException: User needs to be authenticated to call this API.
这是来自 getCurrentUser() 的。

angular amazon-cognito aws-amplify
1个回答
0
投票

尝试在服务器端运行

getCurrentUser()
时,我使用 Next.js 14 遇到了同样的问题。我的问题是,登录是使用另一个用户池客户端(Web/应用程序客户端)进行的,而不是我用来运行的客户端
getCurrentUser()

解决方案是使用相同的用户池客户端(Web/应用程序客户端)进行登录操作并检索当前用户。

© www.soinside.com 2019 - 2024. All rights reserved.