Passing user option to rule/access-token after login

Hi all!

I’m using the vanilla JS SPA SDK and I’d like to pass some user-provided info into the access token. Currently, I’m doing sth like:

options["useroption"] = "useroption-value";
auth0.loginWithRedirect(options);

and I extract the option value from the context.request’s querystring inside a rule like:

var useroption = context.request.query.useroption || context.request.body.useroption || "";
context.accessToken["useroption"] = useroption;

This case works fine if the option is specified before user’s login (i.e. before loginWithRedirect). I was wondering if it’d be possible to pass in custom options to the rule/access-token after a user’s login. I tried that with getTokenSilently:

var options = { useroption: "useroption-value" };
token = await auth0.getTokenSilently(options);

but it seems useroption doesn’t appear in context.request. Any idea if that should work or could be made to work? If no, any other suggestions to achieve the same effect?

Thank you,
George

Hi @george.kollias,

In order to persist the user options after a user logs in, you’d likely need to save the user options in the user’s metadata in the rule with something like:

var useroption = context.request.query.useroption || context.request.body.useroption || null;
if (useroption) {
  user.user_metadata.useroption = useroption;
  context.accessToken["useroption"] = useroption;
} else {
  context.accessToken["useroption"] = user.user_metadata.useroption;
}

Thanks @stephanie.chamblee! Just to clarify, I was wondering if it’d be possible the user option to appear in rule’s context.request as part of calling getTokenSilently (or perhaps another method except loginWithRedirect). Any idea if that’d be possible?

Hi @george.kollias,

I just tested this out, and it looks like when you pass custom parameters in the auth0.getTokenSilently, they are accessible in the rule in context.request.query:

const getToken = () => {
  try {
    auth0.getTokenSilently({
      useroption: "test123"
    });
  } catch (err) {
    console.log("Log out failed", err);
  }
};

This is easier to debug with Real-time Webtask Logs Extension

Also, it may help to see the API reference for getTokenSilently: https://auth0.github.io/auth0-spa-js/classes/auth0client.html#gettokensilently

This request will pull the token from memory when a valid one is available, so it is possible that the rule will not run if there is a valid token available.

1 Like

I think the problem in my case was the token cache in the SDK. If cache is disabled it seems passing options to getTokenSilently works fine. Thank you!

1 Like

Great, I’m glad you were able to get it working!

no worries! Here for you!

Previous message deleted due to SPAM reasons.

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.