コード例 #1
0
        void IPolicyExportExtension.ExportPolicy(
            MetadataExporter exporter,
            PolicyConversionContext context)
        {
            if (exporter == null)
            {
                throw new ArgumentNullException("exporter");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            PolicyAssertionCollection assertions = context.GetBindingAssertions();
            XmlDocument doc = new XmlDocument();

            assertions.Add(doc.CreateElement("wsaw", "UsingAddressing", "http://www.w3.org/2006/05/addressing/wsdl"));

            switch (auth_scheme)
            {
            case AuthenticationSchemes.Basic:
            case AuthenticationSchemes.Digest:
            case AuthenticationSchemes.Negotiate:
            case AuthenticationSchemes.Ntlm:
                assertions.Add(doc.CreateElement("http",
                                                 auth_scheme.ToString() + "Authentication",
                                                 "http://schemas.microsoft.com/ws/06/2004/policy/http"));
                break;
            }
        }
コード例 #2
0
        void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            if (exporter == null)
            {
                throw new ArgumentNullException("exporter");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            PolicyAssertionCollection assertions = context.GetBindingAssertions();
            var doc = new System.Xml.XmlDocument();

            ExportAddressingPolicy(context);
            switch (auth_scheme)
            {
            case AuthenticationSchemes.Basic:
            case AuthenticationSchemes.Digest:
            case AuthenticationSchemes.Negotiate:
            case AuthenticationSchemes.Ntlm:
                assertions.Add(doc.CreateElement("http", auth_scheme.ToString() + "Authentication", "http://schemas.microsoft.com/ws/06/2004/policy/http"));
                break;
            }
            var transportProvider = this as ITransportTokenAssertionProvider;

            if (transportProvider != null)
            {
                var token = transportProvider.GetTransportTokenAssertion();
                assertions.Add(CreateTransportBinding(token));
            }
        }
 public static bool DoesAuthTypeMatch(AuthenticationSchemes authScheme, string authType)
 {
     if ((authType == null) || (authType.Length == 0))
     {
         return (authScheme == AuthenticationSchemes.Anonymous);
     }
     if (authScheme == AuthenticationSchemes.Negotiate)
     {
         return ((authType.Equals("ntlm", StringComparison.OrdinalIgnoreCase) || authType.Equals("kerberos", StringComparison.OrdinalIgnoreCase)) || authType.Equals("negotiate", StringComparison.OrdinalIgnoreCase));
     }
     return authScheme.ToString().Equals(authType, StringComparison.OrdinalIgnoreCase);
 }
 public static bool DoesAuthTypeMatch(AuthenticationSchemes authScheme, string authType)
 {
     if ((authType == null) || (authType.Length == 0))
     {
         return(authScheme == AuthenticationSchemes.Anonymous);
     }
     if (authScheme == AuthenticationSchemes.Negotiate)
     {
         return((authType.Equals("ntlm", StringComparison.OrdinalIgnoreCase) || authType.Equals("kerberos", StringComparison.OrdinalIgnoreCase)) || authType.Equals("negotiate", StringComparison.OrdinalIgnoreCase));
     }
     return(authScheme.ToString().Equals(authType, StringComparison.OrdinalIgnoreCase));
 }
コード例 #5
0
ファイル: HttpUtility.cs プロジェクト: chenmj201601/UMP
        internal static IPrincipal CreateUser(
            string response,
            AuthenticationSchemes scheme,
            string realm,
            string method,
            Func <IIdentity, NetworkCredential> credentialsFinder)
        {
            if (response == null ||
                !response.StartsWith(scheme.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var res = AuthenticationResponse.Parse(response);

            if (res == null)
            {
                return(null);
            }

            var id = res.ToIdentity();

            if (id == null)
            {
                return(null);
            }

            NetworkCredential cred = null;

            try
            {
                cred = credentialsFinder(id);
            }
            catch
            {
            }

            if (cred == null)
            {
                return(null);
            }

            var valid = scheme == AuthenticationSchemes.Basic
                        ? ((HttpBasicIdentity)id).Password == cred.Password
                        : scheme == AuthenticationSchemes.Digest
                          ? ((HttpDigestIdentity)id).IsValid(cred.Password, realm, method, null)
                          : false;

            return(valid
                   ? new GenericPrincipal(id, cred.Roles)
                   : null);
        }
コード例 #6
0
        internal static IPrincipal CreateUser(string response, AuthenticationSchemes scheme, string realm, string method, Func <IIdentity, NetworkCredential> credentialsFinder)
        {
            if ((response == null) || (response.Length == 0))
            {
                return(null);
            }
            if (credentialsFinder == null)
            {
                return(null);
            }
            if ((scheme != AuthenticationSchemes.Basic) && (scheme != AuthenticationSchemes.Digest))
            {
                return(null);
            }
            if (scheme == AuthenticationSchemes.Digest)
            {
                if ((realm == null) || (realm.Length == 0))
                {
                    return(null);
                }
                if ((method == null) || (method.Length == 0))
                {
                    return(null);
                }
            }
            if (!response.StartsWith(scheme.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }
            AuthenticationResponse response2 = AuthenticationResponse.Parse(response);

            if (response2 == null)
            {
                return(null);
            }
            IIdentity identity = response2.ToIdentity();

            if (identity == null)
            {
                return(null);
            }
            NetworkCredential credential = null;

            try
            {
                credential = credentialsFinder(identity);
            }
            catch
            {
            }
            return((credential != null) ? (((scheme != AuthenticationSchemes.Basic) || (((HttpBasicIdentity)identity).Password == credential.Password)) ? (((scheme != AuthenticationSchemes.Digest) || ((HttpDigestIdentity)identity).IsValid(credential.Password, realm, method, null)) ? new GenericPrincipal(identity, credential.Roles) : null) : null) : null);
        }
コード例 #7
0
        public async Task AuthType_RequireAuth_ChallengesAdded(AuthenticationSchemes authType)
        {
            using var baseServer = Utilities.CreateHttpAuthServer(authType, DenyAnoymous, out var address);
            using var server     = Utilities.CreateServerOnExistingQueue(authType, DenyAnoymous, baseServer.Options.RequestQueueName);

            Task <HttpResponseMessage> responseTask = SendRequestAsync(address);

            var contextTask = server.AcceptAsync(Utilities.DefaultTimeout); // Fails when the server shuts down, the challenge happens internally.
            var response    = await responseTask;

            Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.ToString(), StringComparer.OrdinalIgnoreCase);
        }
コード例 #8
0
        public async Task AuthType_RequireAuth_ChallengesAdded(AuthenticationSchemes authType)
        {
            using (var server = Utilities.CreateDynamicHost(authType, DenyAnoymous, out var address, httpContext =>
            {
                throw new NotImplementedException();
            }))
            {
                var response = await SendRequestAsync(address);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.ToString(), StringComparer.OrdinalIgnoreCase);
            }
        }
コード例 #9
0
        public async Task AuthType_RequireAuth_ChallengesAdded(AuthenticationSchemes authType)
        {
            string address;

            using (var server = Utilities.CreateHttpAuthServer(authType, out address))
            {
                Task <HttpResponseMessage> responseTask = SendRequestAsync(address);

                var contextTask = server.GetContextAsync(); // Fails when the server shuts down, the challenge happens internally.
                var response    = await responseTask;
                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.ToString(), StringComparer.OrdinalIgnoreCase);
            }
        }
コード例 #10
0
        private bool authenticateRequest(
            AuthenticationSchemes authScheme, TcpListenerWebSocketContext context)
        {
            var challenge = authScheme == AuthenticationSchemes.Basic
                    ? HttpUtility.CreateBasicAuthChallenge(Realm)
                    : authScheme == AuthenticationSchemes.Digest
                      ? HttpUtility.CreateDigestAuthChallenge(Realm)
                      : null;

            if (challenge == null)
            {
                context.Close(HttpStatusCode.Forbidden);
                return(false);
            }

            var         retry             = -1;
            var         expected          = authScheme.ToString();
            var         realm             = Realm;
            var         credentialsFinder = UserCredentialsFinder;
            Func <bool> auth = null;

            auth = () => {
                retry++;
                if (retry > 99)
                {
                    context.Close(HttpStatusCode.Forbidden);
                    return(false);
                }

                var header = context.Headers ["Authorization"];
                if (header == null ||
                    !header.StartsWith(expected, StringComparison.OrdinalIgnoreCase))
                {
                    context.SendAuthChallenge(challenge);
                    return(auth());
                }

                context.SetUser(authScheme, realm, credentialsFinder);
                if (context.IsAuthenticated)
                {
                    return(true);
                }

                context.SendAuthChallenge(challenge);
                return(auth());
            };

            return(auth());
        }
コード例 #11
0
        internal static IPrincipal CreateUser(string response, AuthenticationSchemes scheme, string realm, string method, Func <IIdentity, NetworkCredential> credentialsFinder)
        {
            if (response == null || !response.StartsWith(scheme.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }
            AuthenticationResponse authenticationResponse = AuthenticationResponse.Parse(response);

            if (authenticationResponse == null)
            {
                return(null);
            }
            IIdentity identity = authenticationResponse.ToIdentity();

            if (identity == null)
            {
                return(null);
            }
            NetworkCredential networkCredential = null;

            try
            {
                networkCredential = credentialsFinder(identity);
            }
            catch
            {
            }
            if (networkCredential == null)
            {
                return(null);
            }
            int num;

            switch (scheme)
            {
            case AuthenticationSchemes.Basic:
                num = ((((HttpBasicIdentity)identity).Password == networkCredential.Password) ? 1 : 0);
                break;

            case AuthenticationSchemes.Digest:
                num = (((HttpDigestIdentity)identity).IsValid(networkCredential.Password, realm, method, null) ? 1 : 0);
                break;

            default:
                num = 0;
                break;
            }
            return((num == 0) ? null : new GenericPrincipal(identity, networkCredential.Roles));
        }
コード例 #12
0
        private bool authenticateRequest(
            AuthenticationSchemes scheme, TcpListenerWebSocketContext context)
        {
            var chal = scheme == AuthenticationSchemes.Basic
                 ? AuthenticationChallenge.CreateBasicChallenge(Realm).ToBasicString()
                 : scheme == AuthenticationSchemes.Digest
                   ? AuthenticationChallenge.CreateDigestChallenge(Realm).ToDigestString()
                   : null;

            if (chal == null)
            {
                context.Close(HttpStatusCode.Forbidden);
                return(false);
            }

            var         retry      = -1;
            var         schm       = scheme.ToString();
            var         realm      = Realm;
            var         credFinder = UserCredentialsFinder;
            Func <bool> auth       = null;

            auth = () => {
                retry++;
                if (retry > 99)
                {
                    context.Close(HttpStatusCode.Forbidden);
                    return(false);
                }

                var res = context.Headers["Authorization"];
                if (res == null || !res.StartsWith(schm, StringComparison.OrdinalIgnoreCase))
                {
                    context.SendAuthenticationChallenge(chal);
                    return(auth());
                }

                context.SetUser(scheme, realm, credFinder);
                if (!context.IsAuthenticated)
                {
                    context.SendAuthenticationChallenge(chal);
                    return(auth());
                }

                return(true);
            };

            return(auth());
        }
コード例 #13
0
        public async Task AuthType_AllowAnonymousButSpecify401_ChallengesAdded(AuthenticationSchemes authType)
        {
            using (var server = Utilities.CreateDynamicHost(authType, AllowAnoymous, out var address, httpContext =>
            {
                Assert.NotNull(httpContext.User);
                Assert.NotNull(httpContext.User.Identity);
                Assert.False(httpContext.User.Identity.IsAuthenticated);
                httpContext.Response.StatusCode = 401;
                return(Task.FromResult(0));
            }))
            {
                var response = await SendRequestAsync(address);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.ToString(), StringComparer.OrdinalIgnoreCase);
            }
        }
コード例 #14
0
        // [InlineData(AuthenticationSchemes.Digest)] // Not implemented
        // [InlineData(AuthenticationSchemes.Basic)] // Can't log in with UseDefaultCredentials
        public async Task AuthTypes_UnathorizedAuthenticatedAuthType_Unauthorized(AuthenticationSchemes authType)
        {
            using (var server = Utilities.CreateDynamicHost(authType, DenyAnoymous, out var address, httpContext =>
            {
                Assert.NotNull(httpContext.User);
                Assert.NotNull(httpContext.User.Identity);
                Assert.True(httpContext.User.Identity.IsAuthenticated);
                return(httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme, null));
            }))
            {
                var response = await SendRequestAsync(address, useDefaultCredentials : true);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                Assert.Single(response.Headers.WwwAuthenticate);
                Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.First().Scheme);
            }
        }
コード例 #15
0
        public async Task AuthTypes_ChallengeWillAskForAllEnabledSchemes(AuthenticationSchemes authType)
        {
            var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            using (var server = Utilities.CreateDynamicHost(authType, AllowAnoymous, out var address, httpContext =>
            {
                Assert.NotNull(httpContext.User);
                Assert.NotNull(httpContext.User.Identity);
                Assert.False(httpContext.User.Identity.IsAuthenticated);
                return(httpContext.ChallengeAsync(HttpSysDefaults.AuthenticationScheme));
            }))
            {
                var response = await SendRequestAsync(address);

                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                Assert.Equal(authTypeList.Count(), response.Headers.WwwAuthenticate.Count);
            }
        }
コード例 #16
0
        public async Task AuthTypes_AuthenticateWithNoUser_NoResults(AuthenticationSchemes authType)
        {
            var authTypeList = authType.ToString().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            using (var server = Utilities.CreateDynamicHost(authType, AllowAnoymous, out var address, async httpContext =>
            {
                Assert.NotNull(httpContext.User);
                Assert.NotNull(httpContext.User.Identity);
                Assert.False(httpContext.User.Identity.IsAuthenticated);
                var authResults = await httpContext.AuthenticateAsync(HttpSysDefaults.AuthenticationScheme);
                Assert.False(authResults.Succeeded);
                Assert.True(authResults.None);
            }))
            {
                var response = await SendRequestAsync(address);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Empty(response.Headers.WwwAuthenticate);
            }
        }
コード例 #17
0
        public async Task AuthType_AllowAnonymousButSpecify401_ChallengesAdded(AuthenticationSchemes authType)
        {
            using var baseServer = Utilities.CreateHttpAuthServer(authType, AllowAnoymous, out var address);
            using var server     = Utilities.CreateServerOnExistingQueue(authType, AllowAnoymous, baseServer.Options.RequestQueueName);

            Task <HttpResponseMessage> responseTask = SendRequestAsync(address);

            var context = await server.AcceptAsync(Utilities.DefaultTimeout);

            Assert.NotNull(context.User);
            Assert.False(context.User.Identity.IsAuthenticated);
            Assert.Equal(authType, context.Response.AuthenticationChallenges);
            context.Response.StatusCode = 401;
            context.Dispose();

            var response = await responseTask;

            Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.ToString(), StringComparer.OrdinalIgnoreCase);
        }
コード例 #18
0
        public async Task AuthType_AllowAnonymousButSpecify401_ChallengesAdded(AuthenticationSchemes authType)
        {
            string address;

            using (var server = Utilities.CreateHttpAuthServer(authType | AuthenticationSchemes.AllowAnonymous, out address))
            {
                Task <HttpResponseMessage> responseTask = SendRequestAsync(address);

                var context = await server.GetContextAsync();

                Assert.NotNull(context.User);
                Assert.False(context.User.Identity.IsAuthenticated);
                Assert.Equal(authType, context.AuthenticationChallenges);
                context.Response.StatusCode = 401;
                context.Dispose();

                var response = await responseTask;
                Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                Assert.Equal(authType.ToString(), response.Headers.WwwAuthenticate.ToString(), StringComparer.OrdinalIgnoreCase);
            }
        }
コード例 #19
0
ファイル: HttpXmlFeed.cs プロジェクト: waffle-iron/nequeo
        /// <summary>
        /// Asynchronous listener callback result.
        /// </summary>
        /// <param name="result">The async result for the current connection.</param>
        private void AsynchronousListenerCallback(IAsyncResult result)
        {
            System.IO.Stream     output   = null;
            HttpListenerRequest  request  = null;
            HttpListenerResponse response = null;

            try
            {
                // Get the callback state.
                HttpListener listener = (HttpListener)result.AsyncState;

                // Call EndGetContext to signal the completion of the asynchronous operation.
                HttpListenerContext context = null;

                try
                {
                    // If we have aborted the server while waiting, catch the exception and terminate
                    context = listener.EndGetContext(result);
                }
                catch (ObjectDisposedException)
                {
                    return;
                }

                // If the context is not null.
                if (context != null)
                {
                    // Is there a collection of imported assemblies.
                    if (_composition.HttpServerContext.Count() < 1)
                    {
                        throw new Exception("No http composition service assemblies have been loaded.");
                    }

                    bool isClientValid = true;

                    // Attempt to validate the client.
                    if (context.User != null)
                    {
                        isClientValid = ClientValidation(context.User, _authenticationSchemes);
                    }

                    // Get the request and response context.
                    request  = context.Request;
                    response = context.Response;

                    // If the user has not been validated.
                    if (!isClientValid)
                    {
                        // Construct a minimal response string.
                        string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html401();
                        byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                        // Get the response OutputStream and write the response to it.
                        response.ContentLength64 = buffer.Length;
                        response.ContentType     = "text/html; charset=utf-8";
                        response.StatusCode      = (int)HttpStatusCode.Unauthorized;
                        response.AddHeader("Content-Language", "en-au");
                        response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                        response.AddHeader("WWW-Authenticate", _authenticationSchemes.ToString());

                        // Get the current response output stream
                        // and write the response to the client.
                        output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);

                        // Properly flush and close the output stream
                        output.Flush();
                        output.Close();
                    }
                    else
                    {
                        // Get the local file path for the resource request.
                        string urlFilePath      = ReaderHttp.GetBaseDirectoryPath() + HttpUtility.UrlDecode(request.Url.AbsolutePath.TrimStart('/').Replace("/", "\\")).TrimEnd('\\');
                        string authMode         = ReaderHttp.GetProviderAuthentication(request.Url, _providerName);
                        bool   httpServiceExits = false;

                        // Get the current directory.
                        string directory = System.IO.Path.GetDirectoryName(urlFilePath);

                        // If no extension exists.
                        if (!System.IO.Path.HasExtension(urlFilePath))
                        {
                            directory = System.IO.Path.GetDirectoryName(urlFilePath + "\\");
                        }

                        // Split the request directories and take the last
                        // directory name as the http service metatadata name
                        // to execute.
                        string[] directories = directory.Split(new char[] { '\\' });

                        // Get a http server context instance and clone the instance.
                        Nequeo.Net.Http.IHttpServerContext[] compositeContextServers = _composition.FindCompositeContext(directories, out httpServiceExits);

                        // If the http service does not exist.
                        if (!httpServiceExits)
                        {
                            // Construct a minimal response string.
                            string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html404();
                            byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                            // Get the response OutputStream and write the response to it.
                            response.ContentLength64 = buffer.Length;
                            response.ContentType     = "text/html; charset=utf-8";
                            response.StatusCode      = (int)HttpStatusCode.NotFound;
                            response.AddHeader("Allow", "POST, PUT, GET, HEAD");
                            response.AddHeader("Content-Language", "en-au");
                            response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                            response.AddHeader("WWW-Authenticate", (String.IsNullOrEmpty(authMode) ? "none" : authMode.ToLower()));

                            // Get the current response output stream
                            // and write the response to the client.
                            output = response.OutputStream;
                            output.Write(buffer, 0, buffer.Length);

                            // Properly flush and close the output stream
                            output.Flush();
                            output.Close();
                        }
                        else
                        {
                            // If composite servers instance exists.
                            if (compositeContextServers != null)
                            {
                                // If composite servers have been found.
                                if (compositeContextServers.Count() > 0)
                                {
                                    // For each composite server found.
                                    foreach (Nequeo.Net.Http.IHttpServerContext httpServer in compositeContextServers)
                                    {
                                        Nequeo.Net.Http.IHttpServerContext instance = httpServer;
                                        try
                                        {
                                            // Determine if the current request is a post back.
                                            bool isPostBack = false;
                                            if ((request.HttpMethod.ToLower().Contains("post")) || (request.HttpMethod.ToLower().Contains("put")))
                                            {
                                                isPostBack = true;
                                            }

                                            // Execute the http service.
                                            ActiveProcessing process = new ActiveProcessing()
                                            {
                                                MimeType   = _contextMimeType,
                                                IsPostBack = isPostBack
                                            };

                                            // Execute the http service.
                                            ActiveHttpContext httpContext = new ActiveHttpContext()
                                            {
                                                Request  = context.Request,
                                                Response = context.Response,
                                                User     = context.User
                                            };

                                            // Create the marshaled server context.
                                            Net.Http.HttpServerContext httpServerContext = new Http.HttpServerContext()
                                            {
                                                HttpContext   = httpContext,
                                                ActiveProcess = process
                                            };

                                            // Process the request.
                                            instance.ProcessHttpRequest(httpServerContext);
                                        }
                                        catch (Exception httpServiceError)
                                        {
                                            // Log the error.
                                            LogHandler.WriteTypeMessage(
                                                httpServiceError.Message,
                                                MethodInfo.GetCurrentMethod(),
                                                Nequeo.Net.Common.Helper.EventApplicationName);
                                        }
                                        finally
                                        {
                                            // Releae the http server reference.
                                            instance = null;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("No http context: HttpListenerContext");
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (response != null)
                    {
                        // Construct a minimal response string.
                        string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html500();
                        byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                        // Get the response OutputStream and write the response to it.
                        response.ContentLength64 = buffer.Length;
                        response.StatusCode      = (int)HttpStatusCode.InternalServerError;
                        response.ContentType     = "text/html; charset=utf-8";
                        response.AddHeader("Content-Language", "en-au");
                        response.AddHeader("Server", "Nequeo/2011.26 (Windows)");

                        // If the response stream has already been activated.
                        if (output == null)
                        {
                            // Get the current response output stream
                            // and write the response to the client.
                            output = response.OutputStream;
                            output.Write(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            output.Write(buffer, 0, buffer.Length);
                        }

                        // Properly flush and close the output stream
                        output.Flush();
                        output.Close();
                    }
                }
                catch (Exception iex)
                {
                    // Log the error.
                    LogHandler.WriteTypeMessage(
                        iex.Message,
                        MethodInfo.GetCurrentMethod(),
                        Nequeo.Net.Common.Helper.EventApplicationName);
                }

                // Log the error.
                LogHandler.WriteTypeMessage(
                    ex.Message,
                    MethodInfo.GetCurrentMethod(),
                    Nequeo.Net.Common.Helper.EventApplicationName);
            }
            finally
            {
                try
                {
                    if (output != null)
                    {
                        output.Close();
                    }
                }
                catch (Exception ex)
                {
                    // Log the error.
                    LogHandler.WriteTypeMessage(
                        ex.Message,
                        MethodInfo.GetCurrentMethod(),
                        Nequeo.Net.Common.Helper.EventApplicationName);
                }
            }
        }
コード例 #20
0
 internal static string ToString(AuthenticationSchemes authScheme)
 {
     return(authScheme.ToString().ToLowerInvariant());
 }
コード例 #21
0
ファイル: HttpUtility.cs プロジェクト: coreystj/WebSocket
        internal static IPrincipal CreateUser(
            string response,
            AuthenticationSchemes scheme,
            string realm,
            string method,
            Func <IIdentity, NetworkCredential> credentialsFinder
            )
        {
            if (response == null || response.Length == 0)
            {
                return(null);
            }

            if (scheme == AuthenticationSchemes.Digest)
            {
                if (realm == null || realm.Length == 0)
                {
                    return(null);
                }

                if (method == null || method.Length == 0)
                {
                    return(null);
                }
            }
            else
            {
                if (scheme != AuthenticationSchemes.Basic)
                {
                    return(null);
                }
            }

            if (credentialsFinder == null)
            {
                return(null);
            }

            var compType = StringComparison.OrdinalIgnoreCase;

            if (response.IndexOf(scheme.ToString(), compType) != 0)
            {
                return(null);
            }

            var res = AuthenticationResponse.Parse(response);

            if (res == null)
            {
                return(null);
            }

            var id = res.ToIdentity();

            if (id == null)
            {
                return(null);
            }

            NetworkCredential cred = null;

            try {
                cred = credentialsFinder(id);
            }
            catch {
            }

            if (cred == null)
            {
                return(null);
            }

            if (scheme == AuthenticationSchemes.Basic)
            {
                var basicId = (HttpBasicIdentity)id;
                return(basicId.Password == cred.Password
               ? new GenericPrincipal(id, cred.Roles)
               : null);
            }

            var digestId = (HttpDigestIdentity)id;

            return(digestId.IsValid(cred.Password, realm, method, null)
             ? new GenericPrincipal(id, cred.Roles)
             : null);
        }
コード例 #22
0
ファイル: HttpListener.Windows.cs プロジェクト: dotnet/corefx
        private ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId,
            out NTAuthentication newContext, ExtendedProtectionPolicy policy, bool isSecureConnection)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, "AuthenticationScheme:" + authenticationScheme.ToString());
            ArrayList challenges = null;
            newContext = null;

            if ((authenticationScheme & AuthenticationSchemes.Negotiate) != 0)
            {
                AddChallenge(ref challenges, AuthConstants.Negotiate);
            }

            if ((authenticationScheme & AuthenticationSchemes.Ntlm) != 0)
            {
                AddChallenge(ref challenges, AuthConstants.NTLM);
            }

            if ((authenticationScheme & AuthenticationSchemes.Digest) != 0)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, "WDigest");
                throw new NotImplementedException();
            }

            if ((authenticationScheme & AuthenticationSchemes.Basic) != 0)
            {
                AddChallenge(ref challenges, "Basic realm =\"" + Realm + "\"");
            }

            return challenges;
        }
コード例 #23
0
        public override void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes bindingElementAuthenticationSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
        {
            // Verify the authentication settings
            AuthenticationSchemes hostSupportedSchemes = HostedTransportConfigurationManager.MetabaseSettings.GetAuthenticationSchemes(virtualPath);

            if ((bindingElementAuthenticationSchemes & hostSupportedSchemes) == 0)
            {
                if (bindingElementAuthenticationSchemes == AuthenticationSchemes.Negotiate ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.Ntlm ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.IntegratedWindowsAuthentication)
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireWindowsAuth));
                }
                else
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireOtherAuth(bindingElementAuthenticationSchemes.ToString())));
                }
            }

            //only use AuthenticationSchemes, which are supported both in IIS and the WCF binding
            bindingElementAuthenticationSchemes &= hostSupportedSchemes;

            if (bindingElementAuthenticationSchemes != AuthenticationSchemes.Anonymous)
            {
                //Compare the ExtendedProtectionPolicy setttings to IIS
                ExtendedProtectionPolicy iisPolicy = HostedTransportConfigurationManager.MetabaseSettings.GetExtendedProtectionPolicy(virtualPath);

                if (iisPolicy == null) //OS doesn't support CBT
                {
                    if (extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always)
                    {
                        throw FxTrace.Exception.AsError(new NotSupportedException(SR.ExtendedProtectionNotSupported));
                    }
                }
                else
                {
                    if (isMetadataListener && ChannelBindingUtility.IsDefaultPolicy(extendedProtectionPolicy))
                    {
                        //push the IIS policy onto the metadataListener if and only if the default policy is
                        //in force. policy for non metadata listeners will still have to match IIS policy.
                        extendedProtectionPolicy = iisPolicy;
                    }
                    else
                    {
                        if (!ChannelBindingUtility.AreEqual(iisPolicy, extendedProtectionPolicy))
                        {
                            string mismatchErrorMessage;
                            if (iisPolicy.PolicyEnforcement != extendedProtectionPolicy.PolicyEnforcement)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyEnforcementMismatch(iisPolicy.PolicyEnforcement, extendedProtectionPolicy.PolicyEnforcement);
                            }
                            else if (iisPolicy.ProtectionScenario != extendedProtectionPolicy.ProtectionScenario)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyScenarioMismatch(iisPolicy.ProtectionScenario, extendedProtectionPolicy.ProtectionScenario);
                            }
                            else
                            {
                                Fx.Assert(iisPolicy.CustomChannelBinding != extendedProtectionPolicy.CustomChannelBinding, "new case in ChannelBindingUtility.AreEqual to account for");
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyCustomChannelBindingMismatch;
                            }

                            if (mismatchErrorMessage != null)
                            {
                                throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(mismatchErrorMessage)));
                            }
                        }

                        //when using the default SPN list we auto generate, we should make sure that the IIS policy is also the default...
                        ServiceNameCollection listenerSpnList = usingDefaultSpnList ? null : extendedProtectionPolicy.CustomServiceNames;
                        if (!ChannelBindingUtility.IsSubset(iisPolicy.CustomServiceNames, listenerSpnList))
                        {
                            throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(SR.Hosting_ExtendedProtectionSPNListNotSubset)));
                        }
                    }
                }
            }



            // Do not set realm for Cassini.
            if (!ServiceHostingEnvironment.IsSimpleApplicationHost)
            {
                // Set the realm
                realm = HostedTransportConfigurationManager.MetabaseSettings.GetRealm(virtualPath);
            }
        }
コード例 #24
0
        internal static IPrincipal CreateUser(
      string response,
      AuthenticationSchemes scheme,
      string realm,
      string method,
      Func<IIdentity, NetworkCredential> credentialsFinder
    )
        {
            if (response == null || response.Length == 0)
            return null;

              if (credentialsFinder == null)
            return null;

              if (!(scheme == AuthenticationSchemes.Basic || scheme == AuthenticationSchemes.Digest))
            return null;

              if (scheme == AuthenticationSchemes.Digest) {
            if (realm == null || realm.Length == 0)
              return null;

            if (method == null || method.Length == 0)
              return null;
              }

              if (!response.StartsWith (scheme.ToString (), StringComparison.OrdinalIgnoreCase))
            return null;

              var res = AuthenticationResponse.Parse (response);
              if (res == null)
            return null;

              var id = res.ToIdentity ();
              if (id == null)
            return null;

              NetworkCredential cred = null;
              try {
            cred = credentialsFinder (id);
              }
              catch {
              }

              if (cred == null)
            return null;

              if (scheme == AuthenticationSchemes.Basic
              && ((HttpBasicIdentity) id).Password != cred.Password
              ) {
            return null;
              }

              if (scheme == AuthenticationSchemes.Digest
              && !((HttpDigestIdentity) id).IsValid (cred.Password, realm, method, null)
              ) {
            return null;
              }

              return new GenericPrincipal (id, cred.Roles);
        }
コード例 #25
0
ファイル: HttpUtility.cs プロジェクト: moby41/websocket-sharp
    internal static IPrincipal CreateUser (
      string response,
      AuthenticationSchemes scheme,
      string realm,
      string method,
      Func<IIdentity, NetworkCredential> credentialsFinder)
    {
      if (response == null ||
          !response.StartsWith (scheme.ToString (), StringComparison.OrdinalIgnoreCase))
        return null;

      var res = AuthenticationResponse.Parse (response);
      if (res == null)
        return null;

      var id = res.ToIdentity ();
      if (id == null)
        return null;

      NetworkCredential cred = null;
      try {
        cred = credentialsFinder (id);
      }
      catch {
      }

      if (cred == null)
        return null;

      var valid = scheme == AuthenticationSchemes.Basic
                  ? ((HttpBasicIdentity) id).Password == cred.Password
                  : scheme == AuthenticationSchemes.Digest
                    ? ((HttpDigestIdentity) id).IsValid (cred.Password, realm, method, null)
                    : false;

      return valid
             ? new GenericPrincipal (id, cred.Roles)
             : null;
    }
コード例 #26
0
 internal static string ToString(AuthenticationSchemes authScheme)
 {
     return authScheme.ToString().ToLowerInvariant();
 }
コード例 #27
0
        public override void ValidateHttpSettings(string virtualPath, bool isMetadataListener, bool usingDefaultSpnList, ref AuthenticationSchemes bindingElementAuthenticationSchemes, ref ExtendedProtectionPolicy extendedProtectionPolicy, ref string realm)
        {
            // Verify the authentication settings
            AuthenticationSchemes hostSupportedSchemes = HostedTransportConfigurationManager.MetabaseSettings.GetAuthenticationSchemes(virtualPath);

            if ((bindingElementAuthenticationSchemes & hostSupportedSchemes) == 0)
            {
                if (bindingElementAuthenticationSchemes == AuthenticationSchemes.Negotiate ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.Ntlm ||
                    bindingElementAuthenticationSchemes == AuthenticationSchemes.IntegratedWindowsAuthentication)
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireWindowsAuth));
                }
                else
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_AuthSchemesRequireOtherAuth(bindingElementAuthenticationSchemes.ToString())));
                }
            }

            //only use AuthenticationSchemes, which are supported both in IIS and the WCF binding
            bindingElementAuthenticationSchemes &= hostSupportedSchemes;

            if (bindingElementAuthenticationSchemes != AuthenticationSchemes.Anonymous)
            {
                //Compare the ExtendedProtectionPolicy setttings to IIS
                ExtendedProtectionPolicy iisPolicy = HostedTransportConfigurationManager.MetabaseSettings.GetExtendedProtectionPolicy(virtualPath);

                if (iisPolicy == null) //OS doesn't support CBT
                {
                    if (extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always)
                    {
                        throw FxTrace.Exception.AsError(new NotSupportedException(SR.ExtendedProtectionNotSupported));
                    }
                }
                else
                {
                    if (isMetadataListener && ChannelBindingUtility.IsDefaultPolicy(extendedProtectionPolicy))
                    {
                        //push the IIS policy onto the metadataListener if and only if the default policy is 
                        //in force. policy for non metadata listeners will still have to match IIS policy.
                        extendedProtectionPolicy = iisPolicy;
                    }
                    else
                    {
                        if (!ChannelBindingUtility.AreEqual(iisPolicy, extendedProtectionPolicy))
                        {
                            string mismatchErrorMessage;
                            if (iisPolicy.PolicyEnforcement != extendedProtectionPolicy.PolicyEnforcement)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyEnforcementMismatch(iisPolicy.PolicyEnforcement, extendedProtectionPolicy.PolicyEnforcement);
                            }
                            else if (iisPolicy.ProtectionScenario != extendedProtectionPolicy.ProtectionScenario)
                            {
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyScenarioMismatch(iisPolicy.ProtectionScenario, extendedProtectionPolicy.ProtectionScenario);
                            }
                            else 
                            {
                                Fx.Assert(iisPolicy.CustomChannelBinding != extendedProtectionPolicy.CustomChannelBinding, "new case in ChannelBindingUtility.AreEqual to account for");
                                mismatchErrorMessage = SR.ExtendedProtectionPolicyCustomChannelBindingMismatch;
                            }

                            if (mismatchErrorMessage != null)
                            {
                                throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(mismatchErrorMessage)));
                            }
                        }

                        //when using the default SPN list we auto generate, we should make sure that the IIS policy is also the default...
                        ServiceNameCollection listenerSpnList = usingDefaultSpnList ? null : extendedProtectionPolicy.CustomServiceNames;
                        if (!ChannelBindingUtility.IsSubset(iisPolicy.CustomServiceNames, listenerSpnList))
                        {
                            throw FxTrace.Exception.AsError(new NotSupportedException(SR.Hosting_ExtendedProtectionPoliciesMustMatch(SR.Hosting_ExtendedProtectionSPNListNotSubset)));
                        }
                    }
                }
            }

            

            // Do not set realm for Cassini.
            if (!ServiceHostingEnvironment.IsSimpleApplicationHost)
            {
                // Set the realm
                realm = HostedTransportConfigurationManager.MetabaseSettings.GetRealm(virtualPath);
            }
        }
コード例 #28
0
        private ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, 
            out NTAuthentication newContext, ExtendedProtectionPolicy policy, bool isSecureConnection)
        {
            GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::BuildChallenge()  authenticationScheme:" + authenticationScheme.ToString());
            ArrayList challenges = null;
            newContext = null;

            if ((authenticationScheme & AuthenticationSchemes.Negotiate) != 0)
            {
                AddChallenge(ref challenges, NegotiateClient.AuthType);
            }

            if ((authenticationScheme & AuthenticationSchemes.Ntlm) != 0)
            {
                AddChallenge(ref challenges, NtlmClient.AuthType);
            }

            if ((authenticationScheme & AuthenticationSchemes.Digest) != 0)
            {
                GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::BuildChallenge() package:WDigest");

                NTAuthentication context = null;
                try
                {
                    string outBlob = null;
                    ChannelBinding binding = GetChannelBinding(connectionId, isSecureConnection, policy);

                    context = new NTAuthentication(true, NegotiationInfoClass.WDigest, null,
                        GetContextFlags(policy, isSecureConnection), binding);

                    SecurityStatus statusCode;
                    outBlob = context.GetOutgoingDigestBlob(null, null, null, Realm, false, false, out statusCode);
                    GlobalLog.Print("HttpListener#" + ValidationHelper.HashString(this) + "::BuildChallenge() GetOutgoingDigestBlob() returned IsCompleted:" + context.IsCompleted + " statusCode:" + statusCode + " outBlob:[" + outBlob + "]");

                    if (context.IsValidContext)
                    {
                        newContext = context;
                    }

                    AddChallenge(ref challenges, DigestClient.AuthType + (string.IsNullOrEmpty(outBlob) ? "" : " " + outBlob));
                }
                finally
                {
                    if (context != null && newContext != context)
                    {
                        context.CloseContext();
                    }
                }
            }

            if ((authenticationScheme & AuthenticationSchemes.Basic) != 0)
            {
                AddChallenge(ref challenges, BasicClient.AuthType + " realm=\"" + Realm + "\"");
            }

            return challenges;
        }
コード例 #29
0
        internal static IPrincipal CreateUser(
            string response,
            AuthenticationSchemes scheme,
            string realm,
            string method,
            Func <IIdentity, NetworkCredential> credentialsFinder)
        {
            if (response == null || response.Length == 0)
            {
                return(null);
            }

            if (credentialsFinder == null)
            {
                return(null);
            }

            if (!(scheme == AuthenticationSchemes.Basic || scheme == AuthenticationSchemes.Digest))
            {
                return(null);
            }

            if (scheme == AuthenticationSchemes.Digest)
            {
                if (realm == null || realm.Length == 0)
                {
                    return(null);
                }

                if (method == null || method.Length == 0)
                {
                    return(null);
                }
            }

            if (!response.StartsWith(scheme.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var res = AuthenticationResponse.Parse(response);

            if (res == null)
            {
                return(null);
            }

            var id = res.ToIdentity();

            if (id == null)
            {
                return(null);
            }

            NetworkCredential cred = null;

            try
            {
                cred = credentialsFinder(id);
            }
            catch
            {
            }

            if (cred == null)
            {
                return(null);
            }

            if (scheme == AuthenticationSchemes.Basic && ((HttpBasicIdentity)id).Password != cred.Password)
            {
                return(null);
            }

            if (scheme == AuthenticationSchemes.Digest && !((HttpDigestIdentity)id).IsValid(cred.Password, realm, method, null))
            {
                return(null);
            }

            return(new GenericPrincipal(id, cred.Roles));
        }
コード例 #30
0
        /// <summary>
        /// Asynchronous listener callback result.
        /// </summary>
        /// <param name="result">The async result for the current connection.</param>
        private void AsynchronousListenerCallback(IAsyncResult result)
        {
            System.IO.Stream     output           = null;
            System.IO.Stream     input            = null;
            System.IO.FileStream localDestination = null;

            HttpListenerRequest  request  = null;
            HttpListenerResponse response = null;

            try
            {
                // Get the callback state.
                HttpListener listener = (HttpListener)result.AsyncState;

                // Call EndGetContext to signal the completion of the asynchronous operation.
                HttpListenerContext context = null;

                try
                {
                    // If we have aborted the server while waiting, catch the exception and terminate
                    context = listener.EndGetContext(result);
                }
                catch (ObjectDisposedException)
                {
                    return;
                }

                // If the context is not null.
                if (context != null)
                {
                    bool isClientValid = true;

                    // Attempt to validate the client.
                    if (context.User != null)
                    {
                        isClientValid = ClientValidation(context.User, _authenticationSchemes);
                    }

                    // Get the request and response context.
                    request  = context.Request;
                    response = context.Response;

                    // If the user has not been validated.
                    if (!isClientValid)
                    {
                        // Construct a minimal response string.
                        string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html401();
                        byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                        // Get the response OutputStream and write the response to it.
                        response.ContentLength64 = buffer.Length;
                        response.ContentType     = "text/html; charset=utf-8";
                        response.StatusCode      = (int)HttpStatusCode.Unauthorized;
                        response.AddHeader("Content-Language", "en-au");
                        response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                        response.AddHeader("WWW-Authenticate", _authenticationSchemes.ToString());

                        // Get the current response output stream
                        // and write the response to the client.
                        output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);

                        // Properly flush and close the output stream
                        output.Flush();
                        output.Close();
                    }
                    else
                    {
                        // Get the local file path for the resource request.
                        string absolutePath = HttpUtility.UrlDecode(request.Url.AbsolutePath.TrimStart('/').Replace("/", "\\"));
                        string urlFilePath  = ReaderHttp.GetBaseDirectoryPath() + absolutePath;
                        string authMode     = ReaderHttp.GetProviderAuthentication(request.Url, _providerName);
                        bool   fileExists   = System.IO.File.Exists(urlFilePath);

                        string uploadFilePath  = null;
                        bool   foundInDownload = false;

                        // Look in the base upload path for the file.
                        if (!fileExists)
                        {
                            // Get the save paths.
                            string[] savePaths = ActiveProcessing.GetSavePaths(_contextMimeType);

                            // If an upload path has been supplied.
                            if (savePaths.Count() > 0)
                            {
                                // For each path found.
                                foreach (string path in savePaths)
                                {
                                    // Get the upload directory.
                                    string   uploadDirectory = path.TrimEnd('\\') + "\\";
                                    string[] directories     = System.IO.Path.GetDirectoryName(absolutePath).Split(new char[] { '\\' });

                                    // For each possible url prefix.
                                    foreach (string prefix in listener.Prefixes)
                                    {
                                        Uri    url = new Uri(prefix);
                                        string prefixAbaolutePath = HttpUtility.UrlDecode(url.AbsolutePath.TrimStart('/').Replace("/", "\\"));

                                        // Get the directory query string.
                                        string directory = "";
                                        foreach (string item in directories)
                                        {
                                            directory += item + "\\";
                                        }

                                        // Get the download file path.
                                        uploadFilePath = uploadDirectory +
                                                         (string.IsNullOrEmpty(directory) ? "" : directory.Replace(prefixAbaolutePath, "").TrimEnd('\\') + "\\") +
                                                         System.IO.Path.GetFileName(urlFilePath);

                                        // Does the file exist.
                                        fileExists = System.IO.File.Exists(uploadFilePath);

                                        // If the file is found in the download path.
                                        if (fileExists)
                                        {
                                            foundInDownload = true;
                                            break;
                                        }
                                    }
                                    if (foundInDownload)
                                    {
                                        break;
                                    }
                                }
                            }
                        }

                        // If the file does not exists then try to load
                        // the default.htm file.
                        if (!fileExists)
                        {
                            string newUrlFilePath = urlFilePath.TrimEnd('\\') + "\\";
                            string newFileName    = System.IO.Path.GetFileName(newUrlFilePath);

                            // Create the new default url file name.
                            if (String.IsNullOrEmpty(newFileName))
                            {
                                urlFilePath = newUrlFilePath + "default.htm";
                                fileExists  = System.IO.File.Exists(urlFilePath);
                            }
                        }

                        // Does the resource exits on the server.
                        if (fileExists)
                        {
                            // Get the extension allow list.
                            string[] extensions = _contextMimeType.fileExtensionAllowList.Split(new char[] { ';' });
                            string   extension  = System.IO.Path.GetExtension(urlFilePath).TrimStart(new char[] { '.' });
                            string   directory  = System.IO.Path.GetDirectoryName(urlFilePath);
                            string   fileName   = System.IO.Path.GetFileName(urlFilePath);

                            // Extension is allowed.
                            if (extensions.Count(u => u.Contains(extension)) > 0 && !foundInDownload)
                            {
                                // Get the specific upload file save paths.
                                string uploaderSavePath          = ActiveProcessing.UploaderSavePath(_contextMimeType, fileName, directory);
                                string uploadedFilesListSavePath = ActiveProcessing.UploadedFilesListSavePath(_contextMimeType, fileName, directory);

                                // If the client is posting back.
                                if (!String.IsNullOrEmpty(request.HttpMethod))
                                {
                                    // If method is anything other then POST, PUT then null.
                                    if ((!request.HttpMethod.ToLower().Contains("post")) && (!request.HttpMethod.ToLower().Contains("put")))
                                    {
                                        // If not posting back then not an uploader operation.
                                        uploaderSavePath = null;
                                    }
                                }
                                else
                                {
                                    // If no request method then no uploader operation.
                                    uploaderSavePath = null;
                                }

                                // If the request is a file uploader.
                                if (!String.IsNullOrEmpty(uploaderSavePath))
                                {
                                    string localFileName = null;
                                    try
                                    {
                                        // Get the maximum upload file size.
                                        long maxUploadFileSize = ActiveProcessing.UploaderMaxUploadFileZise(_contextMimeType, fileName, directory);

                                        // If the file is not to large.
                                        if (request.ContentLength64 <= maxUploadFileSize)
                                        {
                                            // The request is a file uploader.
                                            Nequeo.Net.Http.Utility.CreateDirectory(uploaderSavePath);
                                            localFileName = uploaderSavePath + Guid.NewGuid().ToString() + ".txt";

                                            // Create the new file and start the transfer process.
                                            localDestination = new System.IO.FileStream(localFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
                                            input            = request.InputStream;

                                            // Copy the request stream data to the file stream.
                                            Nequeo.Net.Http.Utility.TransferData(input, localDestination);

                                            // Flush the streams.
                                            input.Flush();
                                            localDestination.Flush();

                                            // Close the local file.
                                            localDestination.Close();
                                            input.Close();

                                            // Construct a minimal response string.
                                            string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html001();
                                            byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                                            // Get the response OutputStream and write the response to it.
                                            response.ContentLength64 = buffer.Length;
                                            response.ContentType     = "text/html; charset=utf-8";
                                            response.AddHeader("Content-Language", "en-au");
                                            response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                                            response.AddHeader("WWW-Authenticate", (String.IsNullOrEmpty(authMode) ? "none" : authMode.ToLower()));

                                            // Get the current response output stream
                                            // and write the response to the client.
                                            output = response.OutputStream;
                                            output.Write(buffer, 0, buffer.Length);

                                            // Properly flush and close the output stream
                                            output.Flush();
                                            output.Close();

                                            // Start a async uploaded file parser.
                                            Action <string> fileParserHandler = new Action <string>(ActiveProcessing.ParseUploadedFile);
                                            IAsyncResult    ar = fileParserHandler.BeginInvoke(localFileName, null, null);
                                        }
                                        else
                                        {
                                            // Construct a minimal response string.
                                            string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html003(maxUploadFileSize);
                                            byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                                            // Get the response OutputStream and write the response to it.
                                            response.ContentLength64 = buffer.Length;
                                            response.StatusCode      = (int)HttpStatusCode.RequestEntityTooLarge;
                                            response.ContentType     = "text/html; charset=utf-8";
                                            response.AddHeader("Content-Language", "en-au");
                                            response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                                            response.AddHeader("WWW-Authenticate", (String.IsNullOrEmpty(authMode) ? "none" : authMode.ToLower()));

                                            // Get the current response output stream
                                            // and write the response to the client.
                                            output = response.OutputStream;
                                            output.Write(buffer, 0, buffer.Length);

                                            // Properly flush and close the output stream
                                            output.Flush();
                                            output.Close();
                                        }
                                    }
                                    catch (Exception upex)
                                    {
                                        // Log the error.
                                        LogHandler.WriteTypeMessage(
                                            upex.Message,
                                            MethodInfo.GetCurrentMethod(),
                                            Nequeo.Net.Common.Helper.EventApplicationName);

                                        // Close the local file.
                                        if (localDestination != null)
                                        {
                                            localDestination.Close();
                                        }

                                        // If the local file exits the delete it.
                                        if (!String.IsNullOrEmpty(localFileName))
                                        {
                                            if (System.IO.File.Exists(localFileName))
                                            {
                                                System.IO.File.Delete(localFileName);
                                            }
                                        }

                                        // Throw the exception.
                                        throw;
                                    }
                                }
                                else
                                {
                                    // If the request is a uploaded file list.
                                    if (!String.IsNullOrEmpty(uploadedFilesListSavePath))
                                    {
                                        // Lock the current thread.
                                        lock (_threadObject)
                                        {
                                            string directoryQuery = "";
                                            try
                                            {
                                                // Get the query string.
                                                NameValueCollection queryString = request.QueryString;

                                                // Delete the file file if requested.
                                                if (queryString != null)
                                                {
                                                    // If the delete file query exists
                                                    if (!String.IsNullOrEmpty(queryString["deletefile"]))
                                                    {
                                                        // Get the file to delete path.
                                                        string fileNameToDelete = uploadedFilesListSavePath.TrimEnd('\\') + "\\" + queryString["deletefile"].Replace("/", "\\");

                                                        // If the file exists then delete the file.
                                                        if (System.IO.File.Exists(fileNameToDelete))
                                                        {
                                                            System.IO.File.Delete(fileNameToDelete);
                                                        }
                                                    }

                                                    // If the delete directory query exists
                                                    if (!String.IsNullOrEmpty(queryString["deletedirectory"]))
                                                    {
                                                        // Get the directory to delete path.
                                                        string directoryToDelete = uploadedFilesListSavePath.TrimEnd('\\') + "\\" + queryString["deletedirectory"].Replace("/", "\\").TrimStart('\\') + "\\";

                                                        // If the directory exists then delete the directory.
                                                        if (System.IO.Directory.Exists(directoryToDelete))
                                                        {
                                                            System.IO.Directory.Delete(directoryToDelete, true);
                                                        }
                                                    }

                                                    // If the directory query exists.
                                                    if (!String.IsNullOrEmpty(queryString["directory"]))
                                                    {
                                                        // Set the directory query string.
                                                        directoryQuery = queryString["directory"];
                                                    }
                                                }
                                            }
                                            catch (Exception delupfex)
                                            {
                                                // Log the error.
                                                LogHandler.WriteTypeMessage(
                                                    delupfex.Message,
                                                    MethodInfo.GetCurrentMethod(),
                                                    Nequeo.Net.Common.Helper.EventApplicationName);
                                            }

                                            // Run the uploaded files list Run-Time Text Templating File Preprocessor
                                            // and write the resulting text to the file (uploadfilelist.htm).
                                            string preUploadedFilesList = Nequeo.Net.Http.Common.HttpResponseContent.GetUploadedFileListHtmlEx(fileName, uploadedFilesListSavePath.TrimEnd('\\') + "\\", directoryQuery);
                                            System.IO.File.WriteAllText(urlFilePath, preUploadedFilesList);
                                        }
                                    }

                                    // Construct a response string.
                                    byte[] buffer        = System.IO.File.ReadAllBytes(urlFilePath);
                                    string extensionBase = ActiveProcessing.GetMimeContentType(_contextMimeType, extension);

                                    // Get the response OutputStream and write the response to it.
                                    response.ContentLength64 = buffer.Length;
                                    response.ContentType     = extensionBase;
                                    response.AddHeader("Allow", "POST, PUT, GET, HEAD");
                                    response.AddHeader("Content-Language", "en-au");
                                    response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                                    response.AddHeader("WWW-Authenticate", (String.IsNullOrEmpty(authMode) ? "none" : authMode.ToLower()));

                                    // Closes the connection 'response.OutputStream' becomes null
                                    // and no data is sent to the client at all. This should only
                                    // be used to abort a connection if the client IP is not allowed.
                                    //response.AddHeader("Connection", "close");

                                    // Get the current response output stream
                                    // and write the response to the client.
                                    output = response.OutputStream;
                                    output.Write(buffer, 0, buffer.Length);

                                    // Properly flush and close the output stream
                                    output.Flush();
                                    output.Close();
                                }
                            }
                            else
                            {
                                // Construct a response string.
                                byte[] buffer = System.IO.File.ReadAllBytes(uploadFilePath);

                                // Get the response OutputStream and write the response to it.
                                response.ContentLength64 = buffer.Length;
                                response.ContentType     = "application/" + extension;
                                response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
                                response.AddHeader("Content-Language", "en-au");
                                response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                                response.AddHeader("WWW-Authenticate", (String.IsNullOrEmpty(authMode) ? "none" : authMode.ToLower()));

                                // Get the current response output stream
                                // and write the response to the client.
                                output = response.OutputStream;
                                output.Write(buffer, 0, buffer.Length);

                                // Properly flush and close the output stream
                                output.Flush();
                                output.Close();
                            }
                        }
                        else
                        {
                            // Construct a minimal response string.
                            string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html404();
                            byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                            // Get the response OutputStream and write the response to it.
                            response.ContentLength64 = buffer.Length;
                            response.ContentType     = "text/html; charset=utf-8";
                            response.StatusCode      = (int)HttpStatusCode.NotFound;
                            response.AddHeader("Allow", "POST, PUT, GET, HEAD");
                            response.AddHeader("Content-Language", "en-au");
                            response.AddHeader("Server", "Nequeo/2011.26 (Windows)");
                            response.AddHeader("WWW-Authenticate", (String.IsNullOrEmpty(authMode) ? "none" : authMode.ToLower()));

                            // Get the current response output stream
                            // and write the response to the client.
                            output = response.OutputStream;
                            output.Write(buffer, 0, buffer.Length);

                            // Properly flush and close the output stream
                            output.Flush();
                            output.Close();
                        }
                    }
                }
                else
                {
                    throw new Exception("No http context: HttpListenerContext");
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (response != null)
                    {
                        // Construct a minimal response string.
                        string responseString = Nequeo.Net.Http.Common.HttpPageContent.Html500();
                        byte[] buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

                        // Get the response OutputStream and write the response to it.
                        response.ContentLength64 = buffer.Length;
                        response.StatusCode      = (int)HttpStatusCode.InternalServerError;
                        response.ContentType     = "text/html; charset=utf-8";
                        response.AddHeader("Content-Language", "en-au");
                        response.AddHeader("Server", "Nequeo/2011.26 (Windows)");

                        // If the response stream has already been activated.
                        if (output == null)
                        {
                            // Get the current response output stream
                            // and write the response to the client.
                            output = response.OutputStream;
                            output.Write(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            output.Write(buffer, 0, buffer.Length);
                        }

                        // Properly flush and close the output stream
                        output.Flush();
                        output.Close();
                    }
                }
                catch (Exception iex)
                {
                    // Log the error.
                    LogHandler.WriteTypeMessage(
                        iex.Message,
                        MethodInfo.GetCurrentMethod(),
                        Nequeo.Net.Common.Helper.EventApplicationName);
                }

                // Log the error.
                LogHandler.WriteTypeMessage(
                    ex.Message,
                    MethodInfo.GetCurrentMethod(),
                    Nequeo.Net.Common.Helper.EventApplicationName);
            }
            finally
            {
                try
                {
                    if (output != null)
                    {
                        output.Close();
                    }
                }
                catch (Exception ex)
                {
                    // Log the error.
                    LogHandler.WriteTypeMessage(
                        ex.Message,
                        MethodInfo.GetCurrentMethod(),
                        Nequeo.Net.Common.Helper.EventApplicationName);
                }

                try
                {
                    if (input != null)
                    {
                        input.Close();
                    }
                }
                catch (Exception ex)
                {
                    // Log the error.
                    LogHandler.WriteTypeMessage(
                        ex.Message,
                        MethodInfo.GetCurrentMethod(),
                        Nequeo.Net.Common.Helper.EventApplicationName);
                }

                try
                {
                    if (localDestination != null)
                    {
                        localDestination.Close();
                    }
                }
                catch (Exception ex)
                {
                    // Log the error.
                    LogHandler.WriteTypeMessage(
                        ex.Message,
                        MethodInfo.GetCurrentMethod(),
                        Nequeo.Net.Common.Helper.EventApplicationName);
                }
            }
        }