Ermir
Ermir

Reputation: 1451

How do I change the OpenIddict client settings when a user tries to log in?

I am trying to implement an OpenIddict client that logs in with Entra, and I have got it working by setting up the client at Startup.cs, where I put in my client details (clientId, clientSecret, tenantId). One of the features I am making is allowing the admin to change these details at runtime and not have to restart the whole server every time these changes are applied.

I have gotten to the point that I can use the built-in callbacks to change the clientId and clientSecret, but changing the tenantId has been proving very difficult. Anyone has run into this issue before?

openIddictBUilder.AddClient(options =>
  options.AddEventHandler<OpenIddictClientEvents.PrepareConfigurationRequestContext>(config =>
    {
      config.UseInlineHandler(async (context) =>
        {
          //change the details here
          var settings = await settingService.getSettings();
          context.Registration.ClinetId = settings.clientId;
          context.Registration.ClientSecret = settings.clientSecret;
          // What do i do with the tenant?
        }
    }
    // more boilerplate code here
    var providers = options.UseWebProviders().AddMicrosoft(options => 
    {
      options.SetClientId("placeholderId")
        .setClientSecret("placeholderSecret")
        .setRedirectUri("callback/login/microsoft")
        .SetTenant("placeholderTenant");
    }
  }
}
 

Upvotes: 0

Views: 82

Answers (1)

Mohammadreza Askari
Mohammadreza Askari

Reputation: 583

Configurations in OpenIddictClientEvents are called only once at application load.

If, like me, you need to change the ClientId value on each Http request, you can use middleware.

This function should be called after app.UseAuthentication();

_ = app.Use(async (context, next) =>
{
    var feature = context.Features.Get<OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreFeature>();
    var clientRegistration = feature?.Transaction?.Options.Registrations
        .Where(x => x.GetType() == typeof(OpenIddict.Client.OpenIddictClientRegistration))
        .FirstOrDefault();
    if (clientRegistration != null
        && context.GetDomain() is string domainName
        && clientRegistration.ClientId != domainName)
        clientRegistration.ClientId = domainName;
    await next();
});

Upvotes: 0

Related Questions