-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Amplify v6 and Next v14 getting UserUnAuthenticatedException: User needs to be authenticated to call this API
when calling from Server Component.
#13966
Comments
UserUnAuthenticatedException: User needs to be authenticated to call this API
when calling from Server Component.UserUnAuthenticatedException: User needs to be authenticated to call this API
when calling from Server Component.
I'm experiencing the same, regardless if using cookies from next/headers or request+response in middleware |
Hi @siphosenkosindhlovu @austinjlaverty can you both confirm the following:
|
Everything is configured on the front end. All cookies are present, I can long them in the Server Component. It even runs properly when deployed to AWS Amplify Hosting. But errors out when running locally witch |
Yep, setting ssr: true, and cookies are in browser storage. Client amplify APIs work when retrieving a user from these stored values. This is the final piece of my migration from v5 to v6. Everything else is functioning great |
@austinjlaverty and @siphosenkosindhlovu, can you share what shape of your client side config looks like? Feel free to redact/remove any sensitive ID's or informaiton. |
Here's what my {
"aws_project_region": "us-east-1",
"aws_cloud_logic_custom": [
{
"name": "stripe",
"endpoint": "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/canary",
"region": "us-east-1"
}
],
"aws_appsync_graphqlEndpoint": "https://xxxxxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql",
"aws_appsync_region": "us-east-1",
"aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
"aws_appsync_apiKey": "xxxxxxxxxxxxxxxxxxxxx",
"aws_cognito_identity_pool_id": "us-east-1:xxxxxxxxxxxxxxxxxxxxxxx",
"aws_cognito_region": "us-east-1",
"aws_user_pools_id": "us-east-xxxxxxxxxxxxxx",
"aws_user_pools_web_client_id": "xxxxxxxxxxxxxxxxxx",
"oauth": {},
"aws_cognito_username_attributes": [
"EMAIL"
],
"aws_cognito_social_providers": [],
"aws_cognito_signup_attributes": [
"EMAIL"
],
"aws_cognito_mfa_configuration": "OFF",
"aws_cognito_mfa_types": [],
"aws_cognito_password_protection_settings": {
"passwordPolicyMinLength": 8,
"passwordPolicyCharacters": [
"REQUIRES_LOWERCASE",
"REQUIRES_UPPERCASE",
"REQUIRES_NUMBERS",
"REQUIRES_SYMBOLS"
]
},
"aws_cognito_verification_mechanisms": [
"EMAIL"
],
"aws_user_files_s3_bucket": "xxxxxxxxxxxxxxxxxxxxxxxx",
"aws_user_files_s3_bucket_region": "us-east-1"
} |
Here is mine: import { type ResourcesConfig } from "aws-amplify";
import { APP_URL } from "@/utils/env";
export const AMPLIFY_CONFIG: ResourcesConfig = {
Auth: {
Cognito: {
userPoolId: process.env.NEXT_PUBLIC_AMPLIFY_USER_POOL_ID!,
userPoolClientId:
process.env.NEXT_PUBLIC_AMPLIFY_USER_POOL_WEB_CLIENT_ID!,
loginWith: {
oauth: {
domain: process.env.NEXT_PUBLIC_AMPLIFY_OAUTH_DOMAIN!,
scopes: ["phone", "email", "profile", "openid"],
redirectSignIn: [`${APP_URL}/login/verify`],
redirectSignOut: [`${APP_URL}/`],
responseType: "code",
},
},
},
},
}; |
After some testing, it briefly worked when I'm behind a VPN (Cloudflare WARP in this instance) but stopped again. |
@siphosenkosindhlovu want to circle back on this question from earlier. After signing in an end user, have the auth tokens been written into browser cookie store? Can you share the shape/values of the cookies in your cookie store? @austinjlaverty, can you also share the shape/value of the cookies in your cookies store as well as clarify which API you're calling when you see this exception happening? We're still trying to reproduce this on our side, but haven't been able to up to this point. |
My app is only using Auth. It interfaces with a separate services API layer built on AWS. I'm attempting to import { cookies } from "next/headers";
import { Amplify } from "aws-amplify";
import {
fetchAuthSession,
getCurrentUser as getCurrentAmplifyUser,
} from "aws-amplify/auth/server";
import { createServerRunner } from "@aws-amplify/adapter-nextjs";
import { AMPLIFY_CONFIG } from "./config";
Amplify.configure(AMPLIFY_CONFIG, {
ssr: true,
});
export const { runWithAmplifyServerContext } = createServerRunner({
config: AMPLIFY_CONFIG,
});
export async function getCurrentUser() {
const user = await runWithAmplifyServerContext({
nextServerContext: { cookies },
operation: async (context) => {
const session = await fetchAuthSession(context);
console.log({ session, cookieStore: cookies() });
//if (!session.tokens) return;
const user = await getCurrentAmplifyUser(context);
console.log({ user });
return user;
},
});
if (!user) {
throw new Error("unauthenticated");
}
return user;
} Upon successfully signing in from the client, cookies are present within the browser storage: The same values are also present when logging the value of {
session: {
tokens: undefined,
credentials: undefined,
identityId: undefined,
userSub: undefined
},
cookieStore: RequestCookies {
_parsed: Map(10) {
'ajs_user_id' => [Object],
'ajs_anonymous_id' => [Object],
'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.LastAuthUser' => [Object],
'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.accessToken' => [Object],
'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.idToken' => [Object],
'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.refreshToken' => [Object],
'CognitoIdentityServiceProvider.XXXXXXXXXXXXXXXXXXXXXXXXXX.google_XXXXXXXXXXXXXXXXXXXXX.clockDrift' => [Object],
},
}
} As a result, everything on the server (components, route handlers, middleware using request+response) all fail to retrieve the authenticated state. However, once the client initializes and invokes My setup is currently working locally and in production using v5. Locally I'm based in SEA, but the AWS project is us-east-1. I have no idea if that helps or might influence any sort of edge case. |
Yep, they're being written to the browser store. When I use Amplify auth client side, it correctly shows as authenticated, but doesn't for SSR like for @austinjlaverty. Here's what's logged from the server:
It's only working when deployed to AWS Amplify. |
@austinjlaverty and @siphosenkosindhlovu, greatly appreciate the detailed responses and follow up here. While we work on reproducing the issue on our side, are either of you able to provide a public, minimal sample repo or possibly invite to a private repo where this is happening? |
@austinjlaverty, is your app also only experiencing this locally (but not when deployed)? |
I get the errors after running Update: No longer getting a network error but the same auth error on Ubuntu WSL. And again, everything works with Docker on the same computer, I guess I'll work that way for now. |
@siphosenkosindhlovu, thanks for following up. Can you see if upgrading to the latest version of Amplify (currently v6.8.2) to see if the issue is resolved? That should resolve any issues that would be the result of a network error, but I'm curious to see if the Auth errors persist when upgrading as well. If it's working in Docker, but not WSL, it may be something tied to support from the WSL side (rather than Amplify). |
@cwomack updated to the latest version of Amplify and it's still the same. Doesn't work on native Windows and WSL. |
@siphosenkosindhlovu the auth error will happen if tokens & userSub is undefined. You want to trace the cause for that. I dont think it is happening directly because of Amplify. Can you check what is happening the storage throughout the flow? |
@cwomack @ashika112 tried on another PC connected to the same network and I'm getting the same errors. I can see the cookies when I console log them, but fetchAuthSession always returns returns undefined tokens. Not sure how to trace the problem further than that. |
@siphosenkosindhlovu, do you have any type of global install on the WSL that could be using a different version of Next.JS? The stack trace shows the following:
This looks like it could be related to the following from the Vercel repo - vercel/next.js#48744 |
@cwomack nope. I don't have any global installs on WSL except for npm itself and corepack |
@siphosenkosindhlovu, thanks for confirming. The more we look into this, the more I'm curious if you see any similar behavior to what the intended fix was from the Next.js team as seen in this PR where they needed to unset the header if the Can you inspect your network requests in the WSL environment to see what the |
@siphosenkosindhlovu, wanted ping you again to see if you saw the above comment and had a chance to look into the |
Is v6 that fundamentally different from v5 that the environment would cause such a strange and silent failure? I also work locally Windows and WSL, and have had to downgrade back to v5 so I can remain productive. There are no errors getting thrown to trace. I suppose I can dig into the content length of the amplify calls, but I'm not convinced. This is an app in production and connected to dozens of endpoints. Surely they would also be running into the same issue using same fetch mechanism? While we used to see that undici issue surface in our vercel logs in the past, this has long since been resolved with next version upgrades (an was never such a consistent or local issue) |
One difference between v5 and v6 is that v6 uses |
Based on the suggestion of siphosenkosindhlovu, I tried using Docker to run the local dev server, and now everything works flawlessly. Looks like I'll also be doing this for now Whatever the issue is, it seems to have started with v6 and is isolated to WSL environments (haven't confirmed with windows node) |
Thanks for the follow up @austinjlaverty and glad to hear that you found a way to proceed. As I mentioned earlier, Amplify v6 uses the I will try to find a Windows environment to run some testing see if I can reproduce this. |
Before opening, please confirm:
JavaScript Framework
Next.js
Amplify APIs
Authentication
Amplify Version
v6
Amplify Categories
auth
Backend
Amplify CLI
Environment information
Describe the bug
Cannot use Amplify server api categories from NextJS server components on local computer, but works on deployment.
This code:
Throws this errror:
The session object undefined
tokens
anduserSub
fields event though the token is correctly set in the client and viewable on the server.Important to note that everything works normally in client components.
Expected behavior
getCurrentUser()
to return the credentials of the currently authenticated user.Reproduction steps
getCurrentUser()
api category.Code Snippet
Log output
aws-exports.js
No response
Manual configuration
No response
Additional configuration
No response
Mobile Device
No response
Mobile Operating System
No response
Mobile Browser
No response
Mobile Browser Version
No response
Additional information and screenshots
No response
The text was updated successfully, but these errors were encountered: