Exemplo n.º 1
0
        /// <summary>
        /// Configures the identity provider attribute resolution.
        /// </summary>
        /// <param name="predicate">The metadata configuration.</param>
        /// <returns>The <see cref="IdentityProviderBuilder"/>.</returns>
        public IdentityProviderBuilder WithAttributeResolution(Action <HttpAuthBuilder> predicate)
        {
            var builder = new HttpAuthBuilder();

            predicate(builder);
            _attributeResolution = builder.Build();
            return(this);
        }
Exemplo n.º 2
0
        public async Task ClientCanCreateConfiguration()
        {
            var url           = "http://www.test.com/webhook";
            var messageStream = "outbound";
            var httpAuth      = new HttpAuth {
                Username = "******", Password = "******"
            };
            var httpHeaders = new List <HttpHeader> {
                new HttpHeader {
                    Name = "testName", Value = "testValue"
                }
            };
            var triggers = new WebhookConfigurationTriggers
            {
                Bounce = new WebhookConfigurationBounceTrigger {
                    Enabled = true, IncludeContent = true
                },
                Click = new WebhookConfigurationClickTrigger {
                    Enabled = true
                },
                Open = new WebhookConfigurationOpenTrigger {
                    Enabled = true, PostFirstOpenOnly = true
                },
                Delivery = new WebhookConfigurationDeliveryTrigger {
                    Enabled = true
                },
                SpamComplaint = new WebhookConfigurationSpamComplaintTrigger {
                    Enabled = true, IncludeContent = true
                }
            };
            var newConfiguration = await _client.CreateWebhookConfigurationAsync(url, messageStream, httpAuth, httpHeaders, triggers);

            Assert.NotNull(newConfiguration.ID);
            Assert.Equal(url, newConfiguration.Url);
            Assert.Equal(messageStream, newConfiguration.MessageStream);
            Assert.Equal(httpAuth.Username, newConfiguration.HttpAuth.Username);
            Assert.Equal(httpAuth.Password, newConfiguration.HttpAuth.Password);
            Assert.Equal(httpHeaders.First().Name, newConfiguration.HttpHeaders.First().Name);
            Assert.Equal(httpHeaders.First().Value, newConfiguration.HttpHeaders.First().Value);
            Assert.Equal(triggers.Bounce.Enabled, newConfiguration.Triggers.Bounce.Enabled);
            Assert.Equal(triggers.Bounce.IncludeContent, newConfiguration.Triggers.Bounce.IncludeContent);
            Assert.Equal(triggers.Open.Enabled, newConfiguration.Triggers.Open.Enabled);
            Assert.Equal(triggers.Open.PostFirstOpenOnly, newConfiguration.Triggers.Open.PostFirstOpenOnly);
            Assert.Equal(triggers.Click.Enabled, newConfiguration.Triggers.Click.Enabled);
            Assert.Equal(triggers.Delivery.Enabled, newConfiguration.Triggers.Delivery.Enabled);
            Assert.Equal(triggers.SpamComplaint.Enabled, newConfiguration.Triggers.SpamComplaint.Enabled);
            Assert.Equal(triggers.SpamComplaint.IncludeContent, newConfiguration.Triggers.SpamComplaint.IncludeContent);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Builds a <see cref="IdentityProvider"/> based on the current builder properties.
        /// </summary>
        /// <returns>A <see cref="IdentityProvider"/>.</returns>
        public HttpAuth Build()
        {
            var config = new HttpAuth();

            if (_clientCertificate != null)
            {
                config.ClientCertificate = _clientCertificate;
            }

            if (_credentials != null)
            {
                config.Credentials = _credentials;
            }

            return(config);
        }
Exemplo n.º 4
0
        public async Task ClientCanEditConfiguration()
        {
            var url           = "http://www.test.com/webhook";
            var messageStream = "outbound";
            var httpAuth      = new HttpAuth {
                Username = "******", Password = "******"
            };
            var httpHeaders = new List <HttpHeader> {
                new HttpHeader {
                    Name = "testName", Value = "testValue"
                }
            };
            var triggers = new WebhookConfigurationTriggers
            {
                Bounce = new WebhookConfigurationBounceTrigger {
                    Enabled = true, IncludeContent = true
                },
                Click = new WebhookConfigurationClickTrigger {
                    Enabled = true
                },
            };
            var oldConfig = await _client.CreateWebhookConfigurationAsync(url, messageStream, httpAuth, httpHeaders, triggers);

            var newUrl      = "http://www.test.com/new-webhook";
            var newHttpAuth = new HttpAuth {
                Username = "******", Password = "******"
            };
            var newHeaders     = new List <HttpHeader>();
            var triggersUpdate = new WebhookConfigurationTriggers
            {
                Click = new WebhookConfigurationClickTrigger {
                    Enabled = false
                }
            };
            var updatedConfig = await _client.EditWebhookConfigurationAsync(oldConfig.ID.Value, newUrl, newHttpAuth,
                                                                            newHeaders, triggersUpdate);

            Assert.Equal(oldConfig.ID, updatedConfig.ID);
            Assert.Equal(oldConfig.MessageStream, updatedConfig.MessageStream);
            Assert.Equal(newHttpAuth.Username, updatedConfig.HttpAuth.Username);
            Assert.Equal(newHttpAuth.Password, updatedConfig.HttpAuth.Password);
            Assert.Equal(newUrl, updatedConfig.Url);
            Assert.Equal(newHeaders, updatedConfig.HttpHeaders);
            Assert.Equal(triggersUpdate.Click.Enabled, updatedConfig.Triggers.Click.Enabled);
            Assert.Equal(triggers.Bounce.Enabled, updatedConfig.Triggers.Bounce.Enabled);
        }
Exemplo n.º 5
0
        public override Task HandleRequestAsyncImpl(HttpConnection p)
        {
            if (filter_mode.IsNull == false)
            {
                var auth = HttpAuth.Parse(p);
                if (auth != null && filter_mode.IsOrContains(auth))
                {
                    return(NaiveUtils.CompletedTask);
                }
                else
                {
                    return(Unauthorized(p));
                }
            }

            if (users != null)
            {
                var auth = HttpAuth.Parse(p);
                if (auth != null)
                {
                    if (users.TryGetValue(auth, out var adapters))
                    {
                        return(HttpInAdapter.HandleByAdapters(p, adapters, Logger));
                    }
                    else
                    {
                        Logger.warning("wrong auth from " + p);
                        if (need_auth == NeedAuth.wrong)
                        {
                            return(Unauthorized(p));
                        }
                    }
                }
            }
            if (need_auth == NeedAuth.always)
            {
                return(Unauthorized(p));
            }
            if (@default.IsNull == false)
            {
                return(HttpInAdapter.HandleByAdapters(p, @default, Logger));
            }
            return(NaiveUtils.CompletedTask);
        }
        /// <summary>
        /// I took code from original Saml2Section.GetConfig() and changed it to get it to work.
        /// </summary>
        public static Saml2Config Create(Saml2Section configElement)
        {
            Saml2Config saml2Config = new Saml2Config();

            if (configElement.Actions.ElementInformation.IsPresent)
            {
                foreach (ActionElement action in configElement
                         .Actions)
                {
                    saml2Config.Actions.Add(new Action
                    {
                        Name = action.Name,
                        Type = action.Type
                    });
                }
            }

            if (true || configElement.AllowedAudienceUris.ElementInformation.IsPresent)
            {
                foreach (AudienceUriElement allowedAudienceUri in configElement.AllowedAudienceUris)
                {
                    saml2Config.AllowedAudienceUris.Add(allowedAudienceUri.Uri);
                }
            }

            if (configElement.AssertionProfile.ElementInformation.IsPresent)
            {
                saml2Config.AssertionProfile.AssertionValidator = configElement.AssertionProfile.AssertionValidator;
            }
            if (configElement.CommonDomainCookie.ElementInformation.IsPresent)
            {
                saml2Config.CommonDomainCookie.Enabled             = configElement.CommonDomainCookie.Enabled;
                saml2Config.CommonDomainCookie.LocalReaderEndpoint =
                    configElement.CommonDomainCookie.LocalReaderEndpoint;
            }

            if (true || configElement.IdentityProviders.ElementInformation.IsPresent)
            {
                saml2Config.IdentityProviderSelectionUrl       = configElement.IdentityProviders.SelectionUrl;
                saml2Config.IdentityProviders.Encodings        = configElement.IdentityProviders.Encodings;
                saml2Config.IdentityProviders.MetadataLocation = configElement.IdentityProviders.MetadataLocation;
                foreach (IdentityProviderElement identityProvider1 in configElement.IdentityProviders)
                {
                    IdentityProvider identityProvider2 = new IdentityProvider
                    {
                        AllowUnsolicitedResponses = identityProvider1.AllowUnsolicitedResponses,
                        Default   = identityProvider1.Default,
                        ForceAuth = identityProvider1.ForceAuth,
                        Id        = identityProvider1.Id,
                        IsPassive = identityProvider1.IsPassive,
                        Name      = identityProvider1.Name,
                        OmitAssertionSignatureCheck = identityProvider1.OmitAssertionSignatureCheck,
                        QuirksMode       = identityProvider1.QuirksMode,
                        ResponseEncoding = identityProvider1.ResponseEncoding
                    };
                    if (identityProvider1.ArtifactResolution.ElementInformation.IsPresent)
                    {
                        HttpAuth httpAuth = new HttpAuth();
                        if (identityProvider1.ArtifactResolution.ClientCertificate.ElementInformation.IsPresent)
                        {
                            httpAuth.ClientCertificate = new Certificate
                            {
                                FindValue     = identityProvider1.ArtifactResolution.ClientCertificate.FindValue,
                                StoreLocation = identityProvider1.ArtifactResolution.ClientCertificate.StoreLocation,
                                StoreName     = identityProvider1.ArtifactResolution.ClientCertificate.StoreName,
                                ValidOnly     = identityProvider1.ArtifactResolution.ClientCertificate.ValidOnly,
                                X509FindType  = identityProvider1.ArtifactResolution.ClientCertificate.X509FindType
                            }
                        }
                        ;
                        if (identityProvider1.ArtifactResolution.Credentials.ElementInformation.IsPresent)
                        {
                            httpAuth.Credentials = new HttpAuthCredentials
                            {
                                Password = identityProvider1.ArtifactResolution.Credentials.Password,
                                Username = identityProvider1.ArtifactResolution.Credentials.Username
                            }
                        }
                        ;
                        identityProvider2.ArtifactResolution = httpAuth;
                    }

                    if (identityProvider1.AttributeQuery.ElementInformation.IsPresent)
                    {
                        HttpAuth httpAuth = new HttpAuth();
                        if (identityProvider1.AttributeQuery.ClientCertificate.ElementInformation.IsPresent)
                        {
                            httpAuth.ClientCertificate = new Certificate
                            {
                                FindValue     = identityProvider1.AttributeQuery.ClientCertificate.FindValue,
                                StoreLocation = identityProvider1.AttributeQuery.ClientCertificate.StoreLocation,
                                StoreName     = identityProvider1.AttributeQuery.ClientCertificate.StoreName,
                                ValidOnly     = identityProvider1.AttributeQuery.ClientCertificate.ValidOnly,
                                X509FindType  = identityProvider1.AttributeQuery.ClientCertificate.X509FindType
                            }
                        }
                        ;
                        if (identityProvider1.AttributeQuery.Credentials.ElementInformation.IsPresent)
                        {
                            httpAuth.Credentials = new HttpAuthCredentials
                            {
                                Password = identityProvider1.AttributeQuery.Credentials.Password,
                                Username = identityProvider1.AttributeQuery.Credentials.Username
                            }
                        }
                        ;
                        identityProvider2.AttributeQuery = httpAuth;
                    }

                    if (identityProvider1.PersistentPseudonym.ElementInformation.IsPresent)
                    {
                        identityProvider2.PersistentPseudonym = new PersistentPseudonym
                        {
                            Mapper = identityProvider1.PersistentPseudonym.Mapper
                        }
                    }
                    ;
                    foreach (CertificateValidationElement certificateValidation in identityProvider1
                             .CertificateValidations)
                    {
                        identityProvider2.CertificateValidations.Add(certificateValidation.Type);
                    }
                    foreach (string allKey in identityProvider1.CommonDomainCookie.AllKeys)
                    {
                        identityProvider2.CommonDomainCookie.Add(identityProvider1.CommonDomainCookie[allKey].Key,
                                                                 identityProvider1.CommonDomainCookie[allKey].Value);
                    }
                    foreach (IdentityProviderEndpointElement endpoint in identityProvider1
                             .Endpoints)
                    {
                        identityProvider2.Endpoints.Add(new IdentityProviderEndpoint
                        {
                            Binding = endpoint.Binding,
                            ForceProtocolBinding = endpoint.ForceProtocolBinding,
                            TokenAccessor        = endpoint.TokenAccessor,
                            Type = endpoint.Type,
                            Url  = endpoint.Url
                        });
                    }
                    saml2Config.IdentityProviders.Add(identityProvider2);
                }
            }

            if (configElement.Logging.ElementInformation.IsPresent)
            {
                saml2Config.Logging.LoggingFactory = configElement.Logging.LoggingFactory;
            }
            if (true || configElement.Metadata.ElementInformation.IsPresent)
            {
                saml2Config.Metadata.ExcludeArtifactEndpoints = configElement.Metadata.ExcludeArtifactEndpoints;
                saml2Config.Metadata.Lifetime = configElement.Metadata.Lifetime;
                if (configElement.Metadata.Organization.ElementInformation.IsPresent)
                {
                    saml2Config.Metadata.Organization = new Organization
                    {
                        Name        = configElement.Metadata.Organization.Name,
                        DisplayName = configElement.Metadata.Organization.DisplayName,
                        Url         = configElement.Metadata.Organization.Url
                    }
                }
                ;
                foreach (ContactElement contact in configElement.Metadata.Contacts)
                {
                    saml2Config.Metadata.Contacts.Add(new Contact
                    {
                        Company   = contact.Company,
                        Email     = contact.Email,
                        GivenName = contact.GivenName,
                        Phone     = contact.Phone,
                        SurName   = contact.SurName,
                        Type      = contact.Type
                    });
                }
                foreach (AttributeElement requestedAttribute in configElement.Metadata
                         .RequestedAttributes)
                {
                    saml2Config.Metadata.RequestedAttributes.Add(new Attribute
                    {
                        IsRequired = requestedAttribute.IsRequired,
                        Name       = requestedAttribute.Name
                    });
                }
            }

            if (true || configElement.ServiceProvider.ElementInformation.IsPresent)
            {
                saml2Config.ServiceProvider.AuthenticationContextComparison =
                    configElement.ServiceProvider.AuthenticationContexts.Comparison;
                saml2Config.ServiceProvider.Id = configElement.ServiceProvider.Id;
                saml2Config.ServiceProvider.NameIdFormatAllowCreate =
                    configElement.ServiceProvider.NameIdFormats.AllowCreate;
                saml2Config.ServiceProvider.Server = configElement.ServiceProvider.Server;
                if (configElement.ServiceProvider.SigningCertificate.ElementInformation.IsPresent)
                {
                    saml2Config.ServiceProvider.SigningCertificate = new Certificate
                    {
                        FindValue     = configElement.ServiceProvider.SigningCertificate.FindValue,
                        StoreLocation = configElement.ServiceProvider.SigningCertificate.StoreLocation,
                        StoreName     = configElement.ServiceProvider.SigningCertificate.StoreName,
                        ValidOnly     = configElement.ServiceProvider.SigningCertificate.ValidOnly,
                        X509FindType  = configElement.ServiceProvider.SigningCertificate.X509FindType
                    }
                }
                ;
                foreach (AuthenticationContextElement authenticationContext in configElement
                         .ServiceProvider.AuthenticationContexts)
                {
                    saml2Config.ServiceProvider.AuthenticationContexts.Add(new AuthenticationContext
                    {
                        Context       = authenticationContext.Context,
                        ReferenceType = authenticationContext.ReferenceType
                    });
                }
                foreach (ServiceProviderEndpointElement endpoint in configElement
                         .ServiceProvider.Endpoints)
                {
                    saml2Config.ServiceProvider.Endpoints.Add(new ServiceProviderEndpoint
                    {
                        Binding     = endpoint.Binding,
                        Index       = endpoint.Index,
                        LocalPath   = endpoint.LocalPath,
                        RedirectUrl = endpoint.RedirectUrl,
                        Type        = endpoint.Type
                    });
                }
                foreach (NameIdFormatElement nameIdFormat in configElement.ServiceProvider
                         .NameIdFormats)
                {
                    saml2Config.ServiceProvider.NameIdFormats.Add(nameIdFormat.Format);
                }
            }

            if (configElement.State.ElementInformation.IsPresent)
            {
                saml2Config.State.StateServiceFactory = configElement.State.StateServiceFactory;
                foreach (StateSettingElement setting in configElement.State.Settings)
                {
                    saml2Config.State.Settings.Add(setting.Name, setting.Value);
                }
            }

            return(saml2Config);
        }
    }
}
        /// <summary>
        /// Gets a response from the IdP based on a message.
        /// </summary>
        /// <param name="endpoint">The IdP endpoint.</param>
        /// <param name="message">The message.</param>
        /// <param name="auth">Basic authentication settings.</param>
        /// <returns>The Stream.</returns>
        public Stream GetResponse(string endpoint, string message, HttpAuth auth, string relayState)
        {
            if (auth != null && auth.ClientCertificate != null && auth.Credentials != null)
            {
                throw new Saml20Exception(string.Format("Artifact resolution cannot specify both client certificate and basic credentials for endpoint {0}", endpoint));
            }

            var binding = CreateSslBinding();

            if (auth != null && auth.ClientCertificate != null)
            {
                // Client certificate auth
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            }

            var request = Message.CreateMessage(binding.MessageVersion, HttpArtifactBindingConstants.SoapAction, new SimpleBodyWriter(message));

            request.Headers.To = new Uri(endpoint);

            var property = new HttpRequestMessageProperty {
                Method = "POST"
            };

            property.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");

            if (auth != null && auth.Credentials != null)
            {
                // Basic http auth over ssl
                var basicAuthzHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(auth.Credentials.Username + ":" + auth.Credentials.Password));
                property.Headers.Add(HttpRequestHeader.Authorization, basicAuthzHeader);
            }

            request.Properties.Add(HttpRequestMessageProperty.Name, property);
            if (relayState != null)
            {
                request.Properties.Add("relayState", relayState);
            }

            var epa = new EndpointAddress(endpoint);

            var factory = new ChannelFactory <IRequestChannel>(binding, epa);

            if (auth != null && auth.ClientCertificate != null)
            {
                // Client certificate
                factory.Credentials.ClientCertificate.Certificate = auth.ClientCertificate;
            }

            var reqChannel = factory.CreateChannel();

            reqChannel.Open();
            var response = reqChannel.Request(request);

            Console.WriteLine(response);
            reqChannel.Close();

            var doc = new XmlDocument {
                PreserveWhitespace = true
            };

            doc.Load(response.GetReaderAtBodyContents());
            var outerXml  = doc.DocumentElement.OuterXml;
            var memStream = new MemoryStream(Encoding.UTF8.GetBytes(outerXml));

            return(memStream);
        }
Exemplo n.º 8
0
        private void _gatewayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _gatewayTimer.Stop();
            if (!GatewayEnabled)
            {
                return;
            }
            for (object actionObject; (actionObject = GetGatewayAction()) != null;)
            {
                GatewayAction.BaseObject action = (GatewayAction.BaseObject)actionObject;
                switch (action.ActionType)
                {
                case GatewayAction.GatewayActionType.GetParentFrameNames:
                {
                    GatewayAction.GetParentFrames frameAction = (GatewayAction.GetParentFrames)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            IFrame frame = null;
                            foreach (string frameName in  _webBrowser.Browser.GetBrowser().GetFrameNames())
                            {
                                if (frameAction.StartingFrame.IsRegex.Value &&
                                    Regex.IsMatch(frameName, frameAction.StartingFrame.Value.Value))
                                {
                                    frame = _webBrowser.Browser.GetBrowser().GetFrame(frameName);
                                }
                                else if (!frameAction.StartingFrame.IsRegex.Value && frameName == frameAction.StartingFrame.Value.Value)
                                {
                                    frame = _webBrowser.Browser.GetBrowser().GetFrame(frameName);
                                }
                            }
                            if (frame != null)
                            {
                                //frameAction.RecursiveFrameList.Add(new FrameDetails() { ExpectedFrameName = frame.AttributeName, Url = frame.Url });
                                while (true)
                                {
                                    frameAction.RecursiveFrameList.Add(new FrameDetails()
                                    {
                                        FrameName = frame.Name, Url = frame.Url
                                    });
                                    if (frame.Parent != null)
                                    {
                                        frame = frame.Parent;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                frameAction.Success = true;
                            }
                        });
                    frameAction.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.FindElementsFrame:
                {
                    GatewayAction.FindElementsFrame findingAction = (GatewayAction.FindElementsFrame)action;
                    _webBrowser.Dispatcher.Invoke(async() =>
                        {
                            foreach (string frameName in _webBrowser.Browser.GetBrowser().GetFrameNames())
                            {
                                IFrame frame = _webBrowser.Browser.GetBrowser().GetFrame(frameName);
                                var result   = await frame.EvaluateScriptAsync(findingAction.EvaluationScript);
                                if (result.Success)
                                {
                                    if ((bool)result.Result)
                                    {
                                        findingAction.FrameName = frameName;
                                        findingAction.Success   = true;
                                        break;
                                    }
                                }
                            }
                        });
                    findingAction.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.EvaluateJavascript:
                {
                    GatewayAction.EvaluateJavascript evaluationAction = (GatewayAction.EvaluateJavascript)action;
                    _webBrowser.Dispatcher.Invoke(async() =>
                        {
                            while (true)
                            {
                                IFrame frame = null;
                                if (evaluationAction.FrameName == null)
                                {
                                    frame = _webBrowser.Browser.GetMainFrame();
                                }
                                else if (evaluationAction.FrameName.IsRegex.Value)
                                {
                                    foreach (var frameName in _webBrowser.Browser.GetBrowser().GetFrameNames())
                                    {
                                        if (Regex.IsMatch(frameName, evaluationAction.FrameName.Value.Value))
                                        {
                                            frame = _webBrowser.Browser.GetBrowser().GetFrame(frameName);
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    frame = _webBrowser.Browser.GetBrowser().GetFrame(evaluationAction.FrameName.Value.Value);
                                }
                                if (frame == null)
                                {
                                    evaluationAction.Success  = false;
                                    evaluationAction.Response = new JavascriptResponse()
                                    {
                                        Message = "Frame not found",
                                        Result  = false,
                                        Success = false,
                                    };
                                    evaluationAction.Completed = true;
                                    break;
                                }
                                JavascriptResponse result =
                                    await
                                    frame.EvaluateScriptAsync(evaluationAction.Script,
                                                              timeout: evaluationAction.Timeout);
                                if (!result.Success)
                                {
                                    if (HandleJavascriptEvaluateResultMessage(result.Message, ref frame,
                                                                              evaluationAction.FrameName.Value.Value))
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        evaluationAction.Success = false;
                                    }
                                }
                                else
                                {
                                    evaluationAction.Success = true;
                                }
                                evaluationAction.Response  = result;
                                evaluationAction.Completed = true;
                                break;
                            }
                        });
                }
                break;

                case GatewayAction.GatewayActionType.GetHttpAuth:
                {
                    GatewayAction.GetHttpAuth getHttpAuth = (GatewayAction.GetHttpAuth)action;
                    bool     success      = false;
                    HttpAuth removingAuth = null;
                    foreach (var handledHttpAuth in _webBrowser.RequestHandler.HandledHttpAuths)
                    {
                        if (getHttpAuth.ExpectedHost.Value.Value == "" ||
                            (getHttpAuth.ExpectedHost.IsRegex.Value &&
                             Regex.IsMatch(handledHttpAuth.Host, getHttpAuth.ExpectedHost.Value.Value) ||
                             !getHttpAuth.ExpectedHost.IsRegex.Value &&
                             handledHttpAuth.Host == getHttpAuth.ExpectedHost.Value.Value))
                        {
                            if (getHttpAuth.ExpectedRealm.Value.Value == "" ||
                                (getHttpAuth.ExpectedRealm.IsRegex.Value &&
                                 Regex.IsMatch(handledHttpAuth.Realm, getHttpAuth.ExpectedRealm.Value.Value) ||
                                 !getHttpAuth.ExpectedRealm.IsRegex.Value &&
                                 handledHttpAuth.Realm == getHttpAuth.ExpectedRealm.Value.Value))
                            {
                                if (getHttpAuth.ExpectedSchemaType == GetHttpAuth.SchemaTypes.Nope ||
                                    (getHttpAuth.ExpectedSchemaType.ToString() == handledHttpAuth.Scheme.ToString()))
                                {
                                    if (getHttpAuth.ExpectedPort == null ||
                                        ((int)getHttpAuth.ExpectedPort == handledHttpAuth.Port))
                                    {
                                        success           = handledHttpAuth.SuccessfullyHandled;
                                        getHttpAuth.Host  = handledHttpAuth.Host;
                                        getHttpAuth.Port  = handledHttpAuth.Port;
                                        getHttpAuth.Realm = handledHttpAuth.Realm;
                                        foreach (var value in Enum.GetValues(typeof(GetHttpAuth.SchemaTypes)))
                                        {
                                            if (value.ToString() == handledHttpAuth.Scheme)
                                            {
                                                getHttpAuth.Scheme = (GetHttpAuth.SchemaTypes)Enum.Parse(typeof(GetHttpAuth.SchemaTypes), value.ToString());
                                                break;
                                            }
                                        }
                                        removingAuth = handledHttpAuth;
                                    }
                                }
                            }
                        }
                    }
                    if (removingAuth != null)
                    {
                        _webBrowser.RequestHandler.HandledHttpAuths.Remove(removingAuth);
                    }
                    getHttpAuth.Success   = success;
                    getHttpAuth.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.SetHttpAuth:
                {
                    GatewayAction.SetHttpAuth httpAuth = (GatewayAction.SetHttpAuth)action;
                    _webBrowser.RequestHandler.PreparedHttpAuths.Add(httpAuth);
                    action.Success   = true;
                    action.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.GetJsDialog:
                {
                    GatewayAction.GetJsDialog jsAction = (GatewayAction.GetJsDialog)action;
                    bool     success          = false;
                    JsDialog removingJsDialog = null;
                    foreach (var handledJsDialog in _webBrowser.JsDialogHandler.HandledJsDialogs)
                    {
                        if (jsAction.ExpectedDefaultPromptValue == null ||
                            (jsAction.ExpectedDefaultPromptValue.IsRegex.Value &&
                             Regex.IsMatch(handledJsDialog.DefaultPromptText, jsAction.ExpectedDefaultPromptValue.Value.Value) ||
                             !jsAction.ExpectedDefaultPromptValue.IsRegex.Value &&
                             handledJsDialog.DefaultPromptText == jsAction.ExpectedDefaultPromptValue.Value.Value))
                        {
                            if (jsAction.ExpectedMessageText == null ||
                                (jsAction.ExpectedMessageText.IsRegex.Value &&
                                 Regex.IsMatch(handledJsDialog.MessageText, jsAction.ExpectedMessageText.Value.Value) ||
                                 !jsAction.ExpectedMessageText.IsRegex.Value &&
                                 handledJsDialog.MessageText == jsAction.ExpectedMessageText.Value.Value))
                            {
                                if (jsAction.ExpectedDialogType == GetJsPrompt.DialogTypes.Nope ||
                                    (jsAction.ExpectedDialogType.ToString() == handledJsDialog.DialogType.ToString()))
                                {
                                    success = handledJsDialog.SucessfullyHandled;
                                    jsAction.MessageText        = handledJsDialog.MessageText;
                                    jsAction.DefaultPromptValue = handledJsDialog.DefaultPromptText;
                                    foreach (var value in Enum.GetValues(typeof(GetJsPrompt.DialogTypes)))
                                    {
                                        if (value.ToString() == handledJsDialog.DialogType.ToString())
                                        {
                                            jsAction.DialogType = (GetJsPrompt.DialogTypes)Enum.Parse(typeof(GetJsPrompt.DialogTypes), value.ToString());
                                            break;
                                        }
                                    }
                                    removingJsDialog = handledJsDialog;
                                }
                            }
                        }
                    }
                    if (removingJsDialog != null)
                    {
                        _webBrowser.JsDialogHandler.HandledJsDialogs.Remove(removingJsDialog);
                    }
                    jsAction.Success   = success;
                    jsAction.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.SetJsDialog:
                {
                    GatewayAction.SetJsDialog jsAction = (GatewayAction.SetJsDialog)action;
                    _webBrowser.JsDialogHandler.PreparedDialogActions.Add(jsAction);
                    action.Success   = true;
                    action.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.ExecuteJavascript:
                {
                    GatewayAction.ExecuteJavascript executeJavascript = (GatewayAction.ExecuteJavascript)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            IFrame frame = null;
                            if (executeJavascript.FrameName == null)
                            {
                                frame = _webBrowser.Browser.GetMainFrame();
                            }
                            else if (executeJavascript.FrameName.IsRegex.Value)
                            {
                                foreach (var frameName in _webBrowser.Browser.GetBrowser().GetFrameNames())
                                {
                                    if (Regex.IsMatch(frameName, executeJavascript.FrameName.Value.Value))
                                    {
                                        frame = _webBrowser.Browser.GetBrowser().GetFrame(frameName);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                frame = _webBrowser.Browser.GetBrowser().GetFrame(executeJavascript.FrameName.Value.Value);
                            }
                            if (frame == null)
                            {
                                executeJavascript.Success = false;
                            }
                            else
                            {
                                frame.ExecuteJavaScriptAsync(executeJavascript.Script);

                                executeJavascript.Success = true;
                            }
                            executeJavascript.Completed = true;
                        });
                }
                break;

                case GatewayAction.GatewayActionType.GetSize:
                {
                    GatewayAction.GetSize getSize = (GatewayAction.GetSize)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            getSize.Width  = (int)_webBrowser.ActualWidth;
                            getSize.Height = (int)_webBrowser.ActualHeight;
                        });
                    getSize.Success   = true;
                    getSize.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.IsBrowserInitiated:
                {
                    GatewayAction.IsBrowserInitiated initiatedAction = (GatewayAction.IsBrowserInitiated)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            initiatedAction.Result = _webBrowser.Browser.IsBrowserInitialized;
                        });
                    initiatedAction.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.SendKeyBoard:
                {
                }
                break;

                case GatewayAction.GatewayActionType.SendMouseClick:
                {
                }
                break;

                case GatewayAction.GatewayActionType.SendMouseWheel:
                {
                    var mouseAction = (GatewayAction.SendMouseWheel)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            //_webBrowser.Browser.SendMouseWheelEvent();
                            //_webBrowser.Browser.SendMouseWheelEvent((int)mouseAction.WhellLocation.X, (int)mouseAction.WhellLocation.Y, mouseAction.DeltaWheelAction.Key, -mouseAction.DeltaWheelAction.ExpectedValue, CefEventFlags.None);
                            if (mouseAction.DeltaWheelAction.Key != 0)
                            {
                                _webBrowser.Browser.SendMouseWheelEvent((int)(mouseAction.WhellLocation.X), (int)(mouseAction.WhellLocation.Y), (int)(-mouseAction.DeltaWheelAction.Key * _internalZoomLevel), 0, CefEventFlags.None);
                            }
                            else
                            {
                                _webBrowser.Browser.SendMouseWheelEvent((int)(mouseAction.WhellLocation.X), (int)(mouseAction.WhellLocation.Y), 0, (int)(-mouseAction.DeltaWheelAction.Value * _internalZoomLevel), CefEventFlags.None);
                            }
                            //MessageBox.Show(_webBrowser, _webBrowser.Browser.ZoomLevel.ToString());
                        });
                    DrawPoint((int)(mouseAction.WhellLocation.X), (int)(mouseAction.WhellLocation.Y));
                    mouseAction.Success   = true;
                    mouseAction.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.SiteLoaded:
                {
                    var site = (GatewayAction.SiteLoaded)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            site.Address = _webBrowser.Browser.Address;
                            site.Success = !_webBrowser.Browser.IsLoading;
                        });
                    site.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.ResourceLoaded:
                {
                    var resource = (GatewayAction.ResourceLoaded)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            foreach (var loadedResource in _webBrowser.RequestHandler.LoadedResources
                                     )
                            {
                                if (resource.FrameName == null && loadedResource.IsMainFrame ||
                                    resource.FrameName != null &&
                                    (resource.FrameName.IsRegex.Value
                                        ? Regex.IsMatch(loadedResource.FrameName, resource.FrameName.Value.Value)
                                        : loadedResource.FrameName == resource.FrameName.Value.Value))
                                {
                                    if (resource.ResourceUrl.IsRegex.Value
                                        ? Regex.IsMatch(loadedResource.Url, resource.ResourceUrl.Value.Value)
                                        : (loadedResource.Url == resource.ResourceUrl.Value.Value))
                                    {
                                        resource.Success  = true;
                                        resource.DateTime = loadedResource.DateTime;
                                    }
                                }
                            }
                        });
                    resource.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.FrameLoaded:
                {
                    var frame = (GatewayAction.FrameLoaded)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            List <FrameLoadingState> frameLoadingStates = _webBrowser.BrowsingState.FrameLoadingStates;
                            foreach (FrameLoadingState state in frameLoadingStates)
                            {
                                if (state.IsMainFrame && frame.FrameName == null || frame.FrameName != null &&
                                    (frame.FrameName.IsRegex.Value
                                        ? Regex.IsMatch(state.FrameName, frame.FrameName.Value.Value)
                                        : frame.FrameName != null &&
                                     state.FrameName == frame.FrameName.Value.Value))
                                {
                                    frame.Success = !state.IsLoading;
                                    break;
                                }
                            }
                        });
                    frame.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.ShowMessageBox:
                {
                    GatewayAction.ShowMessageBox messageBox = (GatewayAction.ShowMessageBox)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            MessageBox.Show(_webBrowser, messageBox.Text);
                        });
                    messageBox.Completed = true;
                }
                break;

                case GatewayAction.GatewayActionType.GetFrameNames:
                {
                    var getFrameNames = (GatewayAction.GetFrameNames)action;
                    _webBrowser.Dispatcher.Invoke(() =>
                        {
                            IFrame mainFrame = _webBrowser.Browser.GetMainFrame();
                            foreach (string frameName in _webBrowser.Browser.GetBrowser().GetFrameNames())
                            {
                                getFrameNames.Frames.Add(frameName, mainFrame.Name == frameName);
                            }
                            getFrameNames.Success = true;
                        });
                    action.Completed = true;
                }
                break;
                }
            }
            _gatewayTimer.Start();
        }
Exemplo n.º 9
0
 private Task Unauthorized(HttpConnection p)
 {
     HttpAuth.SetUnauthorizedHeader(p, text);
     p.Handled = true;
     return(NaiveUtils.CompletedTask);
 }