[solved]getUserToken value mismatch when executed with ajax request


How is it possible that the token has a different value when it is called from a snippet in a resource and when it is from an ajax call in the same resource?

I have this line at the beginning of my snippet:

define( 'TOKEN' , $modx->user->getUserToken( $modx->context->get( 'web' ) );

When the user visits the home page the token has a value.

On this home page i have a button to send an ajax request and the same snippet is executed however the token has a different value

This issue prevents me to execute my ajax requests because the token should match between the main page and the ajax calls

Thank you for your help

The token is session based, so perhaps the Ajax request is somehow seen as a different session. Perhaps it’s running a different context or isn’t providing the cookie values (withCredentials)?

Not sure this is the problem, but the command

$modx->user->getUserToken( $modx->context->get( 'web' ) );

is wrong. If you want the user token for the ‘web’ context you have to call it like this:


Thank you, it works!

it’s weird because in the doc they use it the way i had it:

This is the example from the doc:

if ($token != $modx->user->getUserToken($modx->context->get('key')) { ... }

The term ‘key’ in the docs is meant literally. It’s asking MODX for the ‘key’ of the current context, so MODX would return ‘web’ if that’s the current context. In other words, these are both correct and should work:

$modx->user->getUserToken( $modx->context->get( 'key' ) );
$modx->user->getUserToken( 'web' );

The difference is that the first one would work in other contexts.

Thank you Bob yes you are right