Skip to content
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

id token doesn't contain ClientMetadata after refresh #13379

Open
rashidwiizb opened this issue May 14, 2024 · 8 comments
Open

id token doesn't contain ClientMetadata after refresh #13379

rashidwiizb opened this issue May 14, 2024 · 8 comments
Labels
Auth Related to Auth components/category feature-request Request a new feature VP Version parity issues between v5 and v6

Comments

@rashidwiizb
Copy link

this way I m using signIn
"@aws-amplify/react-native": "^1.1.1",
"aws-amplify": "^6.3.1",
"react-native": "0.73.2",

const userSignIn = await signIn({
username: userName,
password: password,
options: {
clientMetadata: {
roleType: "Student"
}
}
});

I already attache pre token lambda trigger on Cognito for customise the id token . so I get the roleType in it on idTojeb when signing success . But when this idToken expires I get the new id token from amplify itself so in that idToken I didn't get this roleType

@github-actions github-actions bot added the pending-triage Issue is pending triage label May 14, 2024
@mattcreaser
Copy link

Hi @rashidwiizb, react-native is actually part of the amplify-js project. I'll transfer this issue over to that repository.

@mattcreaser mattcreaser transferred this issue from aws-amplify/amplify-android May 14, 2024
@cwomack cwomack self-assigned this May 14, 2024
@cwomack cwomack added Auth Related to Auth components/category question General question and removed pending-triage Issue is pending triage labels May 14, 2024
@cwomack
Copy link
Contributor

cwomack commented May 16, 2024

Hello, @rashidwiizb 👋. I think we may need to understand how your Auth flow is structured to better help here. How are you persisting the roleType field and attaching it to the iDToken? Can you share the lambda hook implementation and how to reproduce this? Thanks!

@cwomack cwomack added the pending-response Issue is pending response from the issue requestor label May 16, 2024
@TomMuehlegger
Copy link

We are facing the same issue. When providing the ClientMetadata to the signIn method, we are getting the right JWT token from Cognito (adding a claim, depending on the ClientMetadata, to the token via the PreTokenGeneration trigger in Cognito).

But when doing the fetchAuthSession({ forceRefresh: true }); via Amplify, the ClientMetadata is not provided to the PreTokenGeneration trigger and thus, this information is missing in the JWT token provided by the fetchAuthSession call.

We are using the latest "aws-amplify" version 6.3.2.
Thanks...

@rashidwiizb
Copy link
Author

Hi @mattcreaser thanks for the reply.

@cwomack my pre-token lambda triggers is

const handler = async (event, context,callback) => {
try {
let roleType = '';
if (event.triggerSource === 'TokenGeneration_Authentication') {
roleType = event.request?.clientMetadata?.roleType;
cachedRoleType = roleType;
} else if (event.triggerSource === 'TokenGeneration_RefreshTokens') {
roleType = cachedRoleType;
}

    event.response = {
        claimsOverrideDetails: {
            claimsToAddOrOverride: {
                'roleType': roleType
            },                
        },
    };

    return callback(null, event);
} catch (error) {
    console.error('Error processing Pre Token Generation:', error);
    throw error;
}

};

export { handler };

when I signin I pass the roleType in ClientMetadata and I get that roletype in idtoken,but when the idtoken is expires amplify itself refresh and get the new idtoken and access token but in that id token the roleType is empty strings "", that mean when refreshing the lambda doesn't get the ClientMetadata . Is there any way to fix this ?

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue requestor label May 17, 2024
@israx
Copy link
Contributor

israx commented May 17, 2024

hello everyone. Passing clientMetadata while refreshing tokens is not supported at this time. However we are aware of this feature and will be working on it. I'll mark this issue as a feature request for now.

@israx israx added feature-request Request a new feature and removed question General question labels May 17, 2024
@cwomack cwomack removed their assignment May 17, 2024
@rashidwiizb
Copy link
Author

Hi @israx

I am configuring AWS Amplify with different user pools and client IDs according to the role I pass to the amplify_Config function. This works correctly, and Amplify is configured with the appropriate pool ID and client ID based on the role.

When I first select the "Student" role, it configures for the student, and then the sign-in happens successfully, and the user is logged in. However, after the current user logs out, if I choose another role and call amplify_Config in useEffect again, it reconfigures correctly. Then, when I call sign-in, Amplify tries to sign in with the previously configured user pool and client ID, resulting in an error.

But when I reload the page after selecting the role and configuring Amplify, it works fine. Is there a way to achieve this without reloading the page?

my amplify_Config

export const amplify_Config = async (role) => {
return new Promise((resolve, reject) => {
let poolId = '';
let clientId = '';
role = role.charAt(0).toUpperCase() + role.slice(1);

    if (role === "Student") {
        poolId = config.AWS_CONFIG.STUDENT_POOL_ID;
        clientId = config.AWS_CONFIG.STUDENT_CLIENT;
    } else if (role === "Teacher") {
        poolId = config.AWS_CONFIG.TEACHER_POOL_ID;
        clientId = config.AWS_CONFIG.TEACHER_CLIENT;
    } else if (role === "Parent") {
        poolId = config.AWS_CONFIG.PARENT_POOL_ID;
        clientId = config.AWS_CONFIG.PARENT_CLIENT;
    }

    // console.log("amp config", { role }, { poolId }, { clientId });
    Amplify.configure({
        Auth: {
            Cognito: {
                userPoolId: poolId,
                userPoolClientId: clientId,
                loginWith: {
                    oauth: {
                        domain: '',
                        responseType: 'code',
                        scopes: config.AWS_CONFIG.SCOPE,
                        redirectSignIn: [''],
                        redirectSignOut: [''],
                    }
                },
            },
        },
    });
    resolve();
});

}

the useeffect and reload in signIn page after selecting role

const reload = () => {
var refresh = localStorage.getItem('reload');
setTimeout(function () {
if (refresh === null) {
window.location.reload();
window.localStorage.setItem('reload', "1");
}
});

setTimeout(function () {
localStorage.removeItem('reload')
}, 1000);
}
}
useEffect(() => {
const config = async() =>{
return await amplify_Config(role);
}
if(role){
dispatch(selecteRole(role));
config();
reload() // page reloading
},[role])

@israx
Copy link
Contributor

israx commented May 21, 2024

Hello @rashidwiizb . Can you try the following ?

  1. call Amplify.getConfigure before calling the signIn API and see if the configure was updated.
  2. listening for the signOut hub event and calling Amplify.configure after that.

If that doesn't work. Can you open a different GH issue regarding the problem with Amplify.configure , so we can assist you in a better way?

@rashidwiizb
Copy link
Author

Hi @israx first I call signOut for current logged user and then I reconfigured the amplify according with passed role after configuring I call Amplify.getConfigure and this gives the new configuration , but after that I call signIn it uses the previous configured client id and userpool id for signing;

Amplify.configure({
Auth: {
Cognito: {
userPoolId: poolId,
userPoolClientId: clientId,
loginWith: {
oauth: {
domain: '',
responseType: 'code',
scopes: config.AWS_CONFIG.SCOPE,
redirectSignIn: [''],
redirectSignOut: [''],
}
},
},
},
});

console.log("new configuration",Amplify.getConfigure());

@cwomack cwomack added the VP Version parity issues between v5 and v6 label May 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Auth Related to Auth components/category feature-request Request a new feature VP Version parity issues between v5 and v6
Projects
None yet
Development

No branches or pull requests

5 participants