How do I specify a custom policy to only the first time a user signs in?

243 views Asked by At

Context

We have created a custom policy used when users are invited to our SPA application. The policy does one time user initialization like creating records in our database by invoking the REST API capabilities. Everything here works as expected: The custom logic is executed and we get and id token back.

The problem starts when we are supposed to get an access token for a protected API when invoking the msal.js method "acquireTokenSilent".

We now see, that the custom policy is executed again, the REST endpoint is once again executed and it's trying to create the user again.

Question

Isn't it possible to get an access token without executing all business logic defined in a custom policy? I thought that getting an acccesstoken was completely separate from the policy, since we are already authenticated when we got the id token.

2

There are 2 answers

0
juunas On

acquireTokenSilent in MSAL.js 1.x uses an iframe that runs through the login with prompt=none.

So in the case of implicit grant flow (which is used here), the answer is that it runs through the login flow every time the token is refreshed. There are a couple choices here:

  1. Make the API endpoint idempotent, i.e. allow calling it multiple times (but ignore the request if the user already exists)
  2. Set a claim on the user that is stored in session state (SSO) and skip the REST API orchestration step if that claim has a value (or you can use the objectIdFromSession claim, which I think is there in the starter template)

The first option is sort of the simplest, and I assume you've already made it like that since it would be called again also when the user logs out and logs back in. It might result in a lot of requests to that API though. To avoid that, you could use the newUser claim or set an extension property on the user after the API call.

0
Jas Suri - MSFT On

When calling acquireTokenSilent(), pass in a new authority for a normal Sign In policy. That Sign In policy needs to have session management (SM-AAD) and the same SM-AAD SM technical profile must be present in a technical profile within your invite policy, such that the user can get SSO via the Sign In policy after using the Invite policy.