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

Next.js 14.2 + Amplify v6 Gen1 遇NotAuthorizedException报错求助

解决Amplify v6 + Next.js 14.2中Middleware认证的NotAuthorizedException错误

问题描述

触发错误:NotAuthorizedException: Unauthenticated access is not supported for this identity pool.,场景为使用Next.js 14.2 + Amplify v6 Gen1,在middleware中尝试获取用户会话实现认证时出现,已完成amplify init、amplify pull等初始化步骤,遵循官方文档操作。

相关代码

middleware.tsx

//@ts-nocheck
import {
  fetchAuthSession,
  getCurrentUser,
  fetchUserAttributes,
} from "aws-amplify/auth/server";
import { NextRequest, NextResponse } from "next/server";
import { runWithAmplifyServerContext } from "./utils/amplifyServerUtils";
export async function middleware(request: NextRequest, response: NextResponse) {
  try {
    let data = {};
    const authenticated = await runWithAmplifyServerContext({
      nextServerContext: { request, response },
      operation: async (contextSpec: any) => {
        try {
          const session = await fetchAuthSession(contextSpec);
          if(session.tokens){

            data = await getCurrentUser(contextSpec);
            let data1 = await fetchUserAttributes(contextSpec);
            data = Object.assign(data, data1);
          }

          return session.tokens !== undefined;
        } catch (error) {
          console.log(error);
          return false;
        }
      },
    });
    if (!authenticated) {
      return NextResponse.redirect(new URL("/login", request.url));
    }

    const headers = new Headers(request.headers);

    headers.set("userData", JSON.stringify(data));
    return NextResponse.next({ request: { headers } });
  } catch (error:any) {
    console.log("Error in middleware")
    console.log(error.message)
    return NextResponse.json({error},{status:405})
  }
}
export const config = {
  matcher: [
    "/api/:path*",  
    "/api/imageCID",
    "/api/ownerDetails",
    "/api/customerDetails",
    "/api/rentalDetails",
    "/api/requirementsDetails",
    "/api/specificationDetails",
    "/api/userProfile",
    "/api/imageCID",
    "/api/basicDetails",
    "/api/geocode",
    "/api/addressSearch",
    "/ViewOwnPost",
    "/ViewPost",
    "/ViewListing",
    "/posty",
    "/create-profile"
  ],
};

amplifyServerUtils.ts

import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import config from './amplifyconfiguration';

export const { runWithAmplifyServerContext } = createServerRunner({
  config
});

解决方案

1. 检查身份池配置

  • 登录AWS控制台,找到对应Cognito身份池
  • 查看"Unauthenticated identities"选项:
    • 如果业务不需要未认证访问,保持禁用状态,确保所有请求都携带合法认证信息
    • 如果需要允许未认证访问,开启该选项并保存配置

2. 修正Middleware逻辑

原代码未针对性处理身份池未授权错误,导致报错暴露,修改后逻辑如下:

//@ts-nocheck
import {
  fetchAuthSession,
  getCurrentUser,
  fetchUserAttributes,
} from "aws-amplify/auth/server";
import { NextRequest, NextResponse } from "next/server";
import { runWithAmplifyServerContext } from "./utils/amplifyServerUtils";

export async function middleware(request: NextRequest, response: NextResponse) {
  // 排除登录页,避免重定向死循环
  if (request.nextUrl.pathname === "/login") {
    return NextResponse.next();
  }

  try {
    let data = {};
    const authenticated = await runWithAmplifyServerContext({
      nextServerContext: { request, response },
      operation: async (contextSpec: any) => {
        try {
          const session = await fetchAuthSession(contextSpec);
          if (session.tokens) {
            const user = await getCurrentUser(contextSpec);
            const attributes = await fetchUserAttributes(contextSpec);
            data = { ...user, ...attributes };
          }
          return session.tokens !== undefined;
        } catch (error: any) {
          // 捕获身份池未授权错误,直接判定为未认证
          if (error.name === "NotAuthorizedException") {
            return false;
          }
          console.error("Auth session fetch failed:", error);
          return false;
        }
      },
    });

    if (!authenticated) {
      return NextResponse.redirect(new URL("/login", request.url));
    }

    const headers = new Headers(request.headers);
    headers.set("userData", JSON.stringify(data));
    return NextResponse.next({ request: { headers } });
  } catch (error: any) {
    console.error("Middleware error:", error.message);
    return NextResponse.json({ error: error.message }, { status: 405 });
  }
}

export const config = {
  matcher: [
    "/api/:path*",
    "/ViewOwnPost",
    "/ViewPost",
    "/ViewListing",
    "/posty",
    "/create-profile"
  ],
};

3. 关键优化点

  • 新增登录页排除逻辑,防止重定向循环
  • 针对性捕获NotAuthorizedException,将其作为未认证状态处理,避免错误扩散
  • 简化用户数据合并逻辑,使用扩展运算符替代Object.assign
  • 优化错误日志输出,便于问题排查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:21:16