Search code examples
asp.net-coreopeniddict

How to customize the authorization error produced by OpenIddict?


I'm using OpenIddict for auth in a .NET Core 2 API. Client side I'm relying on any API errors to follow a custom scheme. However, when e.g. a refresh token has been outdated, I can't seem to find out how to customize the error sent back.

The /token endpoint is never reached, so the error is not under "my control".

The result of the request is a status code 400, with the following JSON:

{"error":"invalid_grant","error_description":"The specified refresh token is no longer valid."}

I've tried to use a custom middleware to catch all status codes (which it does), but the result is returned before the execution of my custom middleware has completed.

How can I properly customize the error or intercept to change it? Thanks!


Solution

  • You can use OpenIddict's event model to customize the token response payloads before they are written to the response stream. Here's an example:

    MyApplyTokenResponseHandler.cs

    public class MyApplyTokenResponseHandler : IOpenIddictServerHandler<ApplyTokenResponseContext>
    {
        public ValueTask HandleAsync(ApplyTokenResponseContext context)
        {
            var response = context.Response;
            if (string.Equals(response.Error, OpenIddictConstants.Errors.InvalidGrant, StringComparison.Ordinal) &&
               !string.IsNullOrEmpty(response.ErrorDescription))
            {
                response.ErrorDescription = "Your customized error";
            }
    
            return default;
        }
    }
    

    Startup.cs

    services.AddOpenIddict()
        .AddCore(options =>
        {
            // ...
        })
    
        .AddServer(options =>
        {
            // ...
            options.AddEventHandler<ApplyTokenResponseContext>(builder =>
                builder.UseSingletonHandler<MyApplyTokenResponseHandler>());
        })
    
        .AddValidation(options =>
        {
            // ...
        });