You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15升级Amplify v6后Cognito Hosted UI无法返回令牌

Angular 15 + Amplify v6 Cognito Hosted UI 认证失败问题

我使用Angular 15框架,将aws-amplify从v5版本升级到v6版本后,针对破坏性变更重构了部分调用,本以为配置已完成,但应用无法完成认证。我判断问题出在Auth服务(这是唯一改动点),当前使用Cognito Hosted UI。

当前Auth服务代码

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;
  }
}

额外信息

  • 配置了Cognito的preAuth和postAuth Lambda触发器,两者均已触发事件,说明问题仅在于Amplify未返回令牌
  • Amplify v5版本中,应用的localStorage会存储认证令牌,但v6版本中没有相关存储内容

Cognito Hosted 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()调用。


内容的提问来源于stack exchange,提问作者user6680

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:27:04