Closed didemkkaslan closed 1 month ago
@didemkkaslan Thanks for opening up the issue. Some clarifying question once signedIn do you re-direct the customers to a new page than that of where the signIn originated from? From looks of the codde you provided that seems to be the case?
Have you followed our guideline on MPA and redirects in the case?
Hi @didemkkaslan thanks for opening this issue, I have some questions for your to help investigation:
Amplify.configure(config, { ssr: true })
(note the second parameter ssr: true
is required)shared/config/configureAmplify.ts
is running on the client-side, is that correct? Could you verify the fetchAuthSession()
call was executed after the completion of your handleMicrosoftSSOSignUp()
call?fetchAuthSession()
failed because the incoming request cookie header doesn't contain auth tokens. Could you verify whether the cookie header value of the corresponding request (you can do this by inspecting the request in Chrome developer tool, network tab)@HuiSF Yes I've configured Amplify on client side using ssr: true .
Calling configureAmplify();
in _app.tsx file and its called on initial page load so long before microsoft signup function is called.
import amplifyconfig from '../../amplifyconfiguration.json';
import { Amplify } from 'aws-amplify';
import { fetchAuthSession } from 'aws-amplify/auth';
import { parseAmplifyConfig } from 'aws-amplify/utils';
import { createKeyValueStorageFromCookieStorageAdapter } from 'aws-amplify/adapter-core';
import { deleteCookie, getCookie, setCookie, getCookies } from 'cookies-next';
import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';
const amplifyConfig = parseAmplifyConfig(amplifyconfig);
const cookieOptions =
process.env.NEXT_PUBLIC_ENV === 'msteams'
? {
domain: 'tab.app.spiky.ai' as string,
sameSite: 'none' as 'lax' | 'strict' | 'none',
secure: true,
}
: {};
const keyValueStorage = createKeyValueStorageFromCookieStorageAdapter({
get(name) {
const value = getCookie(name, cookieOptions);
return { name, value };
},
getAll() {
const cookies = getCookies(cookieOptions);
return Object.keys(cookies).map((name) => ({ name, value: cookies[name] }));
},
set(name, value) {
setCookie(name, value, cookieOptions);
},
delete(name) {
deleteCookie(name, cookieOptions);
},
});
export const getAuthToken = async () => {
const session = await fetchAuthSession({});
return session.tokens?.idToken?.toString() as string;
};
export function configureAmplify() {
Amplify.configure(
{
...amplifyConfig,
Auth: {
...amplifyConfig.Auth,
Cognito: {
...amplifyConfig.Auth?.Cognito,
identityPoolId:
process.env.NEXT_PUBLIC_PLATFORM_COGNITO_IDENTITY_POOL_ID!,
userPoolId: process.env.NEXT_PUBLIC_PLATFORM_COGNITO_USER_POOL_ID!,
userPoolClientId:
process.env.NEXT_PUBLIC_PLATFORM_COGNITO_USER_POOL_WEB_CLIENT_ID!,
},
},
API: {
...amplifyConfig.API,
REST: {
...amplifyConfig.API?.REST,
PlatformCorePublicRestApi: {
endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_ENDPOINT}/public`,
},
PlatformCoreRestApi: {
endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_ENDPOINT}/platform`,
},
PlatformCoreCalendarRestApi: {
endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_ENDPOINT}/calendar-v2`,
},
PlatformCoreTeamsRestApi: {
endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_TEAMS_ENDPOINT}`,
},
PlatformIntegrationRestApi: {
endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_INTEGRATION_REST_API_ENDPOINT}`,
},
PlatformRestApi: {
endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_REST_API_ENDPOINT}`,
},
},
},
},
{
ssr: true,
API: {
REST: {
headers: async () => ({
Authorization: `Bearer ${await getAuthToken()}`,
}),
},
},
},
);
cognitoUserPoolsTokenProvider.setKeyValueStorage(keyValueStorage);
}
UserAlreadyExistsException is thrown here and then I call signIn and here are the following network request two of them has no cookie header and the last one has smth weird
@ashika112 I've also tried to place bunch of import 'aws-amplify/auth/enable-oauth-listener';
at the top of some files like register app.tsx but it didn't fix my problem. Sometimes refreshing the page authenticated returns true and tokens are full. but another refresh causes them to disappear
Hi @didemkkaslan thanks for the details, a few things:
createKeyValueStorageFromCookieStorageAdapter
is not meant to be used for client-side use cases. If you want to custom the CookieStorage used on the client-side, please follow this documentation: https://docs.amplify.aws/gen1/react/build-a-backend/auth/manage-user-session/#update-your-token-saving-mechanism (Please keep in mind that currently adapter-nextjs
doesn't support configuring cookie domain attribute on the server side) signIn()
call?tab.app.spiky.ai
does this match the host of the app you are testing with? (browser ignores mismatched domain cookies if current domain is different from the domain you set)document
type request instead of fetch/xhr
in the Network tab of the dev toolThanks @HuiSF I've checked the cookie store after successful sign in and only the accessToken, refreshToken , clockDrift, signInDetails, and LastAuthUser are exist. idToken is missing. A normal sign in with email & password idToken is generated but with microsoft sso its simply not there.
No tab.app.spiky.ai is not the domain I'm testing right now I'm testing localhost:3000. I've tried to remove custom cookie storage also but that also didn't work for me. I needed the custom cookie storage since we also have microsoft tab app and cookies weren't being stored there ( browser ignored them probably at that time ). Removing it, local storage had all these idtoken, accesstoken cookies but still I get the error.
I have also logged cookie header sent to Nextjs Server ( middleware )
_clck=1cx8bx6%7C2%7Cfpx%7C0%7C1745; hubspotutk=3970d3fef9a2ce6cf0ab058899bfb53d; __hssrc=1; _ga=GA1.1.833332417.1728621328; _gcl_au=1.1.173454892.1728621328; intercom-device-id-klkvftm2=28e6244f-edb0-49de-a5f2-47dd4eb81c0a; loginNumber=1; intercom-id-klkvftm2=21f3ec56-4953-4509-b95a-bc5f4040cfa8; intercom-session-klkvftm2=; hstc=181257784.3970d3fef9a2ce6cf0ab058899bfb53d.1728621327217.1728621327217.1728629861492.2; calendarModalShown=true; com.amplify.Cognito.us-east-2%3Afab77640-b14d-4c3f-9b28-4524f31ce036.identityId=us-east-2%3A17cd0c51-9013-c1c8-1815-d63a1ea89d5b; hssc=181257784.3.1728629861492; _clsk=azmhty%7C1728629941727%7C4%7C1%7Cs.clarity.ms%2Fcollect; _ga_2VPPWD0GX5=GS1.1.1728621327.1.1.1728629941.55.0.0; msal.interaction.status=3d3652ea-07fb-4bd9-aad7-9097b065e5b4; ph_phc_2m70xVenigl1M4tg2yTY6XzoCaZPO1F02xoHk2UAa1V_posthog=%7B%22distinct_id%22%3A%22019265d3-362b-771a-ae71-e228fda59435%22%2C%22%24sesid%22%3A%5B1728629985085%2C%2201927a5e-6bd8-7dbe-91ae-a6de6183c069%22%2C1728629861336%5D%7D
Update: I've added forceRefresh: true
to all the fetchAuthSession's and things started to work. User is successfully authenticated. Serverside fetchAuthSession calls now able to grab tokens. But I'm refreshing the token hundreds of time now and not sure if its the right way.
const session = await fetchAuthSession(contextSpec, {
forceRefresh: true,
});
const hubListenerCancelToken = Hub.listen('auth', async ({ payload }) => {
console.log('auth event', payload);
})
Hi @didemkkaslan it sounds like some of your customizations may not work well to ensure a correct token writing flow. I'm getting lost in the threads of your use cases 😅 could you do the following:
Amplify.configure(config, { ssr: true })
fetchAuthSession
Then please let us know: what's working and what's not working
Hello @HuiSF I'm sorry I know it became a mess :D
I've done them all and it didn't work for me. Minimal sample repo prob is to hard to achieve because we use default cognito sources so my Amplify.configure is full of proces.envs.
I actually suspect idToken not being stored in cookie-storage. I got accessToken, signInDetails and all but idToken is not being stored.
https://github.com/aws-amplify/amplify-js/issues/11649#issuecomment-1641111040 This is also the same case for me. Using default storage I got idToken in localstorage but in cookie storage method its gone.
I've checked the size of it and its around 5000 bytes which goes beyond browser limit and maybe it just droppes.
Hello again:) This issue is solved and the reason this was happening was because indeed idToken was absent. It was an idToken size issue. Since it was bigger than 5000 bytest it was dropping silently. For anyone encountering this kind of session tokens empty problem I wanted to write this. Thanks for your patience and help Amplify team <3
@didemkkaslan, thank you for following up and letting us know! Glad you're unblocked and we'll close out the issue now.
We also have the feature request captured within #11649 tracking this limitation as well, so keep an eye on that/follow it for updates as we have them. Thanks!
Before opening, please confirm:
JavaScript Framework
Next.js
Amplify APIs
Authentication
Amplify Version
v6
Amplify Categories
auth
Backend
CDK
Environment information
Describe the bug
I'm implementing the Microsoft SSO signup/signin feature using msal.js and amplify library. After user signs in with microsoft email (Hub fires signedIn event here ) fetchAuthSession call throws User needs to be authenticated to call this API errors. and session tokens are empty
Expected behavior
Session tokens should be filled after successful sign in
Reproduction steps
Use Amplify's signIn method right after signUp
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