public override async Task <bool> InvokeAsync()
        {
            // Note: the transaction may be already attached when replaying an OWIN request
            // (e.g when using a status code pages middleware re-invoking the OWIN pipeline).
            var transaction = Context.Get <OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName);

            if (transaction == null)
            {
                // Create a new transaction and attach the OWIN request to make it available to the OWIN handlers.
                transaction = await _provider.CreateTransactionAsync();

                transaction.Properties[typeof(IOwinRequest).FullName] = new WeakReference <IOwinRequest>(Request);

                // Attach the OpenIddict server transaction to the OWIN shared dictionary
                // so that it can retrieved while performing sign-in/sign-out operations.
                Context.Set(typeof(OpenIddictServerTransaction).FullName, transaction);
            }

            var context = new ProcessRequestContext(transaction);
            await _provider.DispatchAsync(context);

            if (context.IsRequestHandled)
            {
                return(true);
            }

            else if (context.IsRequestSkipped)
            {
                return(false);
            }

            else if (context.IsRejected)
            {
                var notification = new ProcessErrorResponseContext(transaction)
                {
                    Response = new OpenIddictResponse
                    {
                        Error            = context.Error ?? Errors.InvalidRequest,
                        ErrorDescription = context.ErrorDescription,
                        ErrorUri         = context.ErrorUri
                    }
                };

                await _provider.DispatchAsync(notification);

                if (notification.IsRequestHandled)
                {
                    return(true);
                }

                else if (notification.IsRequestSkipped)
                {
                    return(false);
                }

                throw new InvalidOperationException(new StringBuilder()
                                                    .Append("The OpenID Connect response was not correctly processed. This may indicate ")
                                                    .Append("that the event handler responsible of processing OpenID Connect responses ")
                                                    .Append("was not registered or was explicitly removed from the handlers list.")
                                                    .ToString());
            }

            return(false);
        }
        protected override async Task TeardownCoreAsync()
        {
            // Note: OWIN authentication handlers cannot reliabily write to the response stream
            // from ApplyResponseGrantAsync or ApplyResponseChallengeAsync because these methods
            // are susceptible to be invoked from AuthenticationHandler.OnSendingHeaderCallback,
            // where calling Write or WriteAsync on the response stream may result in a deadlock
            // on hosts using streamed responses. To work around this limitation, this handler
            // doesn't implement ApplyResponseGrantAsync but TeardownCoreAsync, which is never called
            // by AuthenticationHandler.OnSendingHeaderCallback. In theory, this would prevent
            // OpenIddictServerOwinMiddleware from both applying the response grant and allowing
            // the next middleware in the pipeline to alter the response stream but in practice,
            // OpenIddictServerOwinMiddleware is assumed to be the only middleware allowed to write
            // to the response stream when a response grant (sign-in/out or challenge) was applied.

            var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null)
            {
                var transaction = Context.Get <OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName);
                if (transaction == null)
                {
                    throw new InvalidOperationException("An OpenID Connect response cannot be returned from this endpoint.");
                }

                var context = new ProcessChallengeResponseContext(transaction)
                {
                    Response = new OpenIddictResponse
                    {
                        Error            = GetProperty(challenge.Properties, Properties.Error),
                        ErrorDescription = GetProperty(challenge.Properties, Properties.ErrorDescription),
                        ErrorUri         = GetProperty(challenge.Properties, Properties.ErrorUri)
                    }
                };

                await _provider.DispatchAsync(context);

                if (context.IsRequestHandled || context.IsRequestSkipped)
                {
                    return;
                }

                else if (context.IsRejected)
                {
                    var notification = new ProcessErrorResponseContext(transaction)
                    {
                        Response = new OpenIddictResponse
                        {
                            Error            = context.Error ?? Errors.InvalidRequest,
                            ErrorDescription = context.ErrorDescription,
                            ErrorUri         = context.ErrorUri
                        }
                    };

                    await _provider.DispatchAsync(notification);

                    if (notification.IsRequestHandled || context.IsRequestSkipped)
                    {
                        return;
                    }

                    throw new InvalidOperationException(new StringBuilder()
                                                        .Append("The OpenID Connect response was not correctly processed. This may indicate ")
                                                        .Append("that the event handler responsible of processing OpenID Connect responses ")
                                                        .Append("was not registered or was explicitly removed from the handlers list.")
                                                        .ToString());
                }