admin管理员组

文章数量:1355099

I am using MSAL to acquire a token from AzureAD, and then I will use this token for every FlUrl call.

To keep the MSAL token auto-refresh working, I need to call MSAL's AcquireToken before every FlUrl call. So I am going to implement the BeforeCall event in the way bellow.

  1. Is this the right approach?
  2. Can I get CancellationToken in some way in FlurlEventHandler.HandleAsync?
public sealed class FlurlBeforeCallAuthProviderHandler : FlurlEventHandler
{
    private static readonly NLog.Logger _log = NLog.LogManager.GetCurrentClassLogger();
    private readonly IMsAuthService _msAuthService;

    public FlurlBeforeCallAuthProviderHandler(IMsAuthService msAuthService)
    {
        _msAuthService = msAuthService;
    }

    public override async Task HandleAsync(FlurlEventType eventType, FlurlCall call)
    {
        _log.Debug("HandleAsync()");
        AuthenticationResult authResult = await _msAuthService.AcquireToken(["api://XXXXXXX/API.Read"], 0,
            ???cancellationToken???);
    call.Request.WithOAuthBearerToken(authResult.AccessToken);
    }
}

and the cache registration:

container.RegisterFactory<IFlurlClientCache>(c => new FlurlClientCache()
    // all clients:
    .WithDefaults(builder =>
    {
        builder.EventHandlers.Add((FlurlEventType.BeforeCall, new FlurlBeforeCallAuthProviderHandler(c.Resolve<IMsAuthService>())));
        .WithHeaders(new
        {
            User_Agent = "SciaDevOpsManager",
        });
    }), FactoryLifetime.Singleton);

本文标签: FlUrl AcquireToken before each requestMSAL authenticationStack Overflow