Search code examples
c#.netoauth-2.0openiddict

How to authenticate OpenIddict' custom grant type using OpenIddictClientService?


OpenIddict server allows me to add custom grant types via .AddServer.AllowCustomFlow. However, I do not see any appropriate method on the OpenIddictClientService which would allow me to call this custom flow. It looks like OpenIddictClientService supports only baked-in flows.

Is there any workaround where I could use OpenIddict.Client library and call a custom grant type published by the OpenIddict.Server?


Solution

  • Edit: client support for custom grant types was added in OpenIddict 5.4.0:

    var result = await _service.AuthenticateWithCustomGrantAsync(new()
    {
        AdditionalTokenRequestParameters = new()
        {
            ["my-custom-parameter"] = "value"
        },
        CancellationToken = stoppingToken,
        GrantType = "my-custom-grant-type",
        ProviderName = provider,
        Scopes = [Scopes.OfflineAccess, Scopes.OpenId]
    });
    

    When using a custom grant type, the following logic is enforced by default:

    • A token request is always sent.
    • An access token MUST be returned as part of the token response.
    • An identity token MAY be returned as part of the token response but it's not mandatory (in this case, OpenIddict will resolve it and extract the principal it contains, but won't reject the response if it's invalid).
    • A refresh token MAY be returned as part of the token response but it's not mandatory.
    • A userinfo request is always sent when an access token was returned and a userinfo endpoint is available, unless userinfo retrieval was explicitly disabled when calling AuthenticateWithCustomGrantAsync().

    To customize the default logic, creating custom IOpenIddictClientHandler<ProcessAuthenticationContext> handlers will be required.


    As you figured out, it's currently not a supported scenario. Depending on the demand, it's something that may be added in a future version. But in this case, it will very likely require adding multiple IOpenIddictClientHandler<ProcessAuthenticationContext> handlers to indicate to OpenIddict how to behave with your custom grant.