public static object HookAuthentication(this OwinRequest request, IAuthenticationHandler handler)
        {
            var chained = request.Get <AuthenticateDelegate>("security.Authenticate");
            var hook    = new Hook(handler, chained);

            request.Set <AuthenticateDelegate>("security.Authenticate", hook.Authenticate);
            return(hook);
        }
        /// <summary>
        /// Creates request OWIN respresentation. 
        /// </summary>
        /// <param name="method">The request method.</param>
        /// <param name="scheme">The request scheme.</param>
        /// <param name="pathBase">The request base path.</param>
        /// <param name="path">The request path.</param>
        /// <param name="headers">The request headers.</param>
        /// <param name="queryString">The request query string</param>
        /// <param name="requestBody">The body of request.</param>
        /// <returns>OWIN representation for provided request parameters.</returns>
        private static Dictionary<string, object> CreateOwinEnvironment(string method, string scheme, string pathBase, 
                                                                        string path, IDictionary<string, string[]> headers, string queryString = "", byte[] requestBody = null)
        {
            var environment = new Dictionary<string, object>(StringComparer.Ordinal);
            environment[CommonOwinKeys.OwinCallCancelled] = new CancellationToken();

            #region OWIN request params

            var request = new OwinRequest(environment)
                {
                    Method = method,
                    Scheme = scheme,
                    Path = new PathString(path),
                    PathBase = new PathString(pathBase),
                    QueryString = new QueryString(queryString),
                    Body = new MemoryStream(requestBody ?? new byte[0]),
                    Protocol = Protocols.Http1
                };

            // request.Headers is readonly
            request.Set(CommonOwinKeys.RequestHeaders, headers);

            #endregion


            #region set default OWIN response params

            var response = new OwinResponse(environment) {Body = new MemoryStream(), StatusCode = StatusCode.Code200Ok};
            //response.Headers is readonly
            response.Set(CommonOwinKeys.ResponseHeaders, new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase));

            #endregion


            return environment;
        }
        public static void UnhookAuthentication(this OwinRequest request, object state)
        {
            var hook = (Hook)state;

            request.Set("security.Authenticate", hook.Chained);
        }