public DefaultWebCrawlerService(ICmsConfiguration cmsConfiguration)
        {
            this.cmsConfiguration = cmsConfiguration;

            webServer = cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneWebSiteUrl) ?? string.Empty;

            bool.TryParse(cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneIndexPrivatePages), out indexPrivatePages);

            if (indexPrivatePages)
            {
                var authModeString = cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneAuthorizationMode);
                if (!string.IsNullOrWhiteSpace(authModeString))
                {
                    switch (authModeString.ToLower().Trim())
                    {
                        case "windows":
                            authMode = AuthMode.Windows;
                            break;
                        default:
                            authMode = AuthMode.Forms;
                            break;
                    }
                }
            }

            HtmlAgilityPackHelper.FixMissingTagClosings();

            TimeSpan timeout;
            if (TimeSpan.TryParse(cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneIndexerPageFetchTimeout), out timeout)
                && timeout > TimeSpan.FromSeconds(0))
            {
                fetchTimeout = timeout;
            }
        }
示例#2
0
        internal PrtgClient(string server, string username, string password, AuthMode authMode, IWebClient client,
                            IXmlSerializer xmlSerializer = null)
        {
            if (xmlSerializer == null)
            {
                xmlSerializer = new XmlExpressionSerializer();
            }

            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            if (username == null)
            {
                throw new ArgumentNullException(nameof(username));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            RequestEngine = new RequestEngine(this, client);

            ConnectionDetails = new ConnectionDetails(server, username, password);
            Targets           = new PrtgTargetHelper(this);

            if (authMode == AuthMode.Password)
            {
                ConnectionDetails.PassHash = GetPassHash(password);
            }

            ObjectEngine = new ObjectEngine(this, RequestEngine, xmlSerializer);
        }
 /// <summary>
 /// Copy client policy from another client policy.
 /// </summary>
 public ClientPolicy(ClientPolicy other)
 {
     this.user                 = other.user;
     this.password             = other.password;
     this.clusterName          = other.clusterName;
     this.authMode             = other.authMode;
     this.timeout              = other.timeout;
     this.loginTimeout         = other.loginTimeout;
     this.maxConnsPerNode      = other.maxConnsPerNode;
     this.connPoolsPerNode     = other.connPoolsPerNode;
     this.maxSocketIdle        = other.maxSocketIdle;
     this.tendInterval         = other.tendInterval;
     this.failIfNotConnected   = other.failIfNotConnected;
     this.readPolicyDefault    = new Policy(other.readPolicyDefault);
     this.writePolicyDefault   = new WritePolicy(other.writePolicyDefault);
     this.scanPolicyDefault    = new ScanPolicy(other.scanPolicyDefault);
     this.queryPolicyDefault   = new QueryPolicy(other.queryPolicyDefault);
     this.batchPolicyDefault   = new BatchPolicy(other.batchPolicyDefault);
     this.infoPolicyDefault    = new InfoPolicy(other.infoPolicyDefault);
     this.tlsPolicy            = (other.tlsPolicy != null) ? new TlsPolicy(other.tlsPolicy) : null;
     this.ipMap                = other.ipMap;
     this.useServicesAlternate = other.useServicesAlternate;
     this.rackAware            = other.rackAware;
     this.rackId               = other.rackId;
 }
        /// <summary>
        /// Logins the specified user name.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="secret">The secret.</param>
        /// <param name="authMode">The authentication mode.</param>
        /// <returns></returns>
        public bool Login(string userName, string secret, AuthMode authMode = AuthMode.AccessKey)
        {
            var loginTask = LoginAsync(userName, secret, authMode);

            loginTask.Wait();
            return(loginTask?.Result ?? false);
        }
        public bool Validate()
        {
            if (!AuthMode.OrdinalEquals("Basic") && !AuthMode.OrdinalEquals("Cloud"))
            {
                return(false);
            }

            if (AuthMode.OrdinalEquals("Basic"))
            {
                if (string.IsNullOrEmpty(TenancyName) || string.IsNullOrEmpty(UsernameOrEmailAddress) || string.IsNullOrEmpty(Password))
                {
                    return(false);
                }
            }

            if (AuthMode.OrdinalEquals("Cloud"))
            {
                if (string.IsNullOrEmpty(RefreshToken) || string.IsNullOrEmpty(ServiceInstanceLogicalName) || string.IsNullOrEmpty(AccountLogicalName))
                {
                    return(false);
                }
            }

            bool isUrl = Uri.IsWellFormedUriString(BaseUrl, UriKind.Absolute);

            if (!isUrl)
            {
                return(false);
            }

            if (!Strategy.OrdinalEquals("Specific") && !Strategy.OrdinalEquals("JobsCount"))
            {
                return(false);
            }

            if (Strategy.OrdinalEquals("Specific") && (RobotIds == null || RobotIds.Length == 0))
            {
                return(false);
            }

            if (Strategy.OrdinalEquals("JobsCount") && JobsCount <= 0)
            {
                return(false);
            }

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

            foreach (var processKey in ProcessKeys)
            {
                if (!Guid.TryParse(processKey.Key, out Guid newGuid))
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Call once to initialize the static variables
        /// </summary>
        public static void Initialize(bool force = false)
        {
            if (IsInitialized && !force)
            {
                return;
            }
            LoadCredentials();

            //Inspect the given Azure Key to see if this is host with appid auth
            string[] AuthComponents = _AzureKey.Split('?');
            if (AuthComponents.Length > 1)
            {
                EndPointAddress = AuthComponents[0];
                string[] appidComponents = AuthComponents[1].ToLowerInvariant().Split('=');
                if (appidComponents[0] == "appid")
                {
                    authMode = AuthMode.AppId;
                    appid    = appidComponents[1];
                }
                else
                {
                    return;
                }
            }
            GetLanguages();
            IsInitialized = true;
        }
        public AzureClient(int portalId, AuthMode mode)
            : base(portalId, mode, "AzureB2C")
        {
            Settings = new AzureConfig("AzureB2C", portalId);

            TokenMethod = HttpMethod.POST;

            if (!string.IsNullOrEmpty(Settings.TenantName) && !string.IsNullOrEmpty(Settings.TenantId))
            {
                TokenEndpoint         = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.TokenEndpointPattern", TokenEndpointPattern), Settings.TenantName, Settings.TenantId));
                LogoutEndpoint        = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.LogoutEndpointPattern", LogoutEndpointPattern), Settings.TenantName, Settings.TenantId, Settings.SignUpPolicy, UrlEncode(HttpContext.Current.Request.Url.ToString())));
                AuthorizationEndpoint = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.AuthorizationEndpointPattern", AuthorizationEndpointPattern), Settings.TenantName, Settings.TenantId));
                MeGraphEndpoint       = new Uri(string.Format(Utils.GetAppSetting("AzureADB2C.GraphEndpointPattern", GraphEndpointPattern), Settings.TenantId));
            }

            if (string.IsNullOrEmpty(Settings.APIResource) && string.IsNullOrEmpty(Settings.Scopes))
            {
                Scope       = Settings.APIKey;
                APIResource = Settings.APIKey;
            }
            else
            {
                Scope = string.Join(" ", Settings.Scopes
                                    .Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                                    .Select(x => $"{Settings.APIResource}{x.Trim()}"));
                APIResource = Settings.APIResource;
            }
            APIKey          = Settings.APIKey;
            AuthTokenName   = "AzureB2CUserToken";
            OAuthVersion    = "2.0";
            OAuthHeaderCode = "Basic";
            LoadTokenCookie(string.Empty);
            JwtIdToken = null;
            Policy     = PolicyEnum.SignUpPolicy;
        }
        public DefaultWebCrawlerService(ICmsConfiguration cmsConfiguration)
        {
            this.cmsConfiguration = cmsConfiguration;

            webServer = cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneWebSiteUrl) ?? string.Empty;

            bool.TryParse(cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneIndexPrivatePages), out indexPrivatePages);

            if (indexPrivatePages)
            {
                var authModeString = cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneAuthorizationMode);
                if (!string.IsNullOrWhiteSpace(authModeString))
                {
                    switch (authModeString.ToLower().Trim())
                    {
                        case "windows":
                            authMode = AuthMode.Windows;
                            break;
                        default:
                            authMode = AuthMode.Forms;
                            break;
                    }
                }
            }

            HtmlAgilityPackHelper.FixMissingTagClosings();

            TimeSpan timeout;
            if (TimeSpan.TryParse(cmsConfiguration.Search.GetValue(LuceneSearchConstants.ConfigurationKeys.LuceneIndexerPageFetchTimeout), out timeout)
                && timeout > TimeSpan.FromSeconds(0))
            {
                fetchTimeout = timeout;
            }
        }
示例#9
0
        protected void BankDD_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblMandateModes.SelectedValue == "E_MANDATE")
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("AuthModeText", typeof(string));
                dt.Columns.Add("AuthModeVal", typeof(string));
                JArray MandateAuthModes = (JArray)Session["MandateAuthModes"];

                JArray SelectedAuthModes = (JArray)MandateAuthModes.Where(a => a["BankCode"].ToString() == BankDD.SelectedValue).Select(b => b["AuthModes"]).First();
                foreach (var AuthMode in SelectedAuthModes)
                {
                    dt.Rows.Add(new object[] { AuthMode.ToString().Replace("_", " "), AuthMode });
                }

                rblAuthType.DataSource = dt;
                rblAuthType.DataBind();
                pnlAuthMode.Visible = true;
            }
            else
            {
                rblAuthType.DataSource = null;
                rblAuthType.DataBind();
                pnlAuthMode.Visible = false;
            }

            EnableAccountDetails();
        }
示例#10
0
        }                                                //To do - make this private

        #endregion

        #region Constructors
        public SpproBaseContext(ClientContext clientContext, AuthMode authMode = AuthMode.Default)
        {
            this.ClientContext = clientContext;
            //Mixed authentication was causing problems so manually set to windows auth
            if (authMode == AuthMode.Windows)
            {
                ClientContext.ExecutingWebRequest += new EventHandler <WebRequestEventArgs>(Headers.MixedAuthentication.ctx_MixedAuthRequest);
            }

            var type = this.GetType();

            foreach (var property in type.GetProperties())
            {
                if (typeof(SpproBaseRepository).IsAssignableFrom(property.PropertyType))
                {
                    var listType    = property.PropertyType; // typeof(SpproRepository<>);
                    var genericArgs = property.PropertyType.GetGenericArguments();
                    //var concreteType = listType.MakeGenericType(genericArgs);
                    var listName         = genericArgs[0].Name;
                    var customAttributes = genericArgs[0].GetCustomAttributes(typeof(SpproListAttribute), true);
                    if (customAttributes.Length > 0 && !string.IsNullOrWhiteSpace(((SpproListAttribute)customAttributes[0]).ListName))
                    {
                        listName = ((SpproListAttribute)customAttributes[0]).ListName;
                    }
                    //var newRepo = Activator.CreateInstance(concreteType, listName, clientContext);
                    var newRepo = Activator.CreateInstance(listType, listName, clientContext);
                    property.SetValue(this, newRepo);
                }
            }
        }
示例#11
0
        /// <summary>
        /// Returns true if OutputCredentialsInfo instances are equal
        /// </summary>
        /// <param name="other">Instance of OutputCredentialsInfo to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(OutputCredentialsInfo other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Description == other.Description ||
                     Description != null &&
                     Description.Equals(other.Description)
                     ) &&
                 (
                     Key == other.Key ||
                     Key != null &&
                     Key.Equals(other.Key)
                 ) &&
                 (
                     Cert == other.Cert ||
                     Cert != null &&
                     Cert.Equals(other.Cert)
                 ) &&
                 (
                     AuthMode == other.AuthMode ||
                     AuthMode != null &&
                     AuthMode.Equals(other.AuthMode)
                 ) &&
                 (
                     SCAL == other.SCAL ||
                     SCAL != null &&
                     SCAL.Equals(other.SCAL)
                 ) &&
                 (
                     PIN == other.PIN ||
                     PIN != null &&
                     PIN.Equals(other.PIN)
                 ) &&
                 (
                     OTP == other.OTP ||
                     OTP != null &&
                     OTP.Equals(other.OTP)
                 ) &&
                 (
                     Multisign == other.Multisign ||
                     Multisign != null &&
                     Multisign.Equals(other.Multisign)
                 ) &&
                 (
                     Lang == other.Lang ||
                     Lang != null &&
                     Lang.Equals(other.Lang)
                 ));
        }
        public OidcClient(int portalId, AuthMode mode)
            : base(portalId, mode, "Oidc")
        {
            AuthorizationEndpoint = "https://localhost:5001/connect/authorize";
            TokenEndpoint         = "https://localhost:5001/connect/token";
            UserInfoEndpoint      = "https://localhost:5001/connect/userinfo";

            Scope = HttpUtility.UrlEncode("openid profile offline_access api1");
        }
示例#13
0
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="baseUrl">API base url</param>
        /// <param name="authMode">Authentication mode</param>
        /// <param name="requestMode">Serialization mode</param>
        protected AppClient(string baseUrl, AuthMode authMode, RequestMode requestMode)
        {
            _baseUrl     = baseUrl;
            _authMode    = authMode;
            _requestMode = requestMode;

            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("User-Agent", $"Disboard/{Version}");
        }
 /// <summary>
 /// Generic GET method
 /// </summary>
 /// <param name="url">Complete REST++ API URL including path and parameters</param>
 /// <param name="authMode">Authentication mode, one of 'token' (default) or 'pwd'</param>
 /// <param name="headers">Standard HTTP request headers (dict)</param>
 /// <param name="resKey">the JSON subdocument to be returned, default is 'result'</param>
 /// <param name="skipCheck">Skip error checking? Some endpoints return error to indicate that the requested action is not applicable; a problem, but not really an error.</param>
 /// <param name="parms">Request URL parameters.</param>
 /// <returns>Dictionary in most cases</returns>
 dynamic Get(string url, AuthMode authMode = AuthMode.Token, Dictionary <string, string> headers = null, string resKey = "results", bool skipCheck = false, Dictionary <string, object> parms = null)
 {
     try
     {
         return(Req(Method.GET, url, authMode, headers, resKey, skipCheck, null, parms));
     }
     catch (Exception ex)
     {
         throw GetException("Get", ex);
     }
 }
 /// <summary>
 /// Generic Post
 /// </summary>
 /// <param name="url">Complete REST++ API URL including path and parameters</param>
 /// <param name="authMode">Authentication mode, one of 'token' (default) or 'pwd'</param>
 /// <param name="headers">Standard HTTP request headers (dict)</param>
 /// <param name="data">Request payload, typically a JSON document</param>
 /// <param name="resKey">the JSON subdocument to be returned, default is 'result'</param>
 /// <param name="skipCheck">Skip error checking? Some endpoints return error to indicate that the requested action is not applicable; a problem, but not really an error.</param>
 /// <param name="parms">Request URL parameters.</param>
 /// <returns></returns>
 dynamic Post(string url, AuthMode authMode, Dictionary <string, string> headers = null, string data = null, string resKey = "results", bool skipCheck = false, string parms = null)
 {
     try
     {
         return(Req(Method.POST, url, authMode, headers, resKey, skipCheck, data));
     }
     catch (Exception ex)
     {
         throw GetException("Post", ex);
     }
 }
示例#16
0
        public LinkedInClient(int portalId, AuthMode mode) : base(portalId, mode, "LinkedIn")
        {
            TokenEndpoint         = new Uri("https://www.linkedin.com/uas/oauth2/accessToken");
            TokenMethod           = HttpMethod.POST;
            AuthorizationEndpoint = new Uri("https://www.linkedin.com/uas/oauth2/authorization");
            MeGraphEndpoint       = new Uri("https://api.linkedin.com/v1/people/~?format=json");

            Scope         = HttpUtility.UrlEncode("r_basicprofile r_emailaddress");
            AuthTokenName = "LinkedInUserToken";
            OAuthVersion  = "2.0";
            LoadTokenCookie(String.Empty);
        }
示例#17
0
        private void btnDefaultAuth_Click(object sender, EventArgs e)
        {
            _authMode = AuthMode.Simple;
            btnDefaultAuth.Hide();
            picGMailLogin.Show();
            picOutlook.Show();
            picYahoo.Show();
            wbrMain.Navigate("about:blank");
            wbrMain.Hide();

            pnlLogin.Show();
        }
示例#18
0
        private void picOutlook_Click(object sender, EventArgs e)
        {
            _authMode = AuthMode.Outlook;

            wbrMain.Show();
            pnlLogin.Hide();
            btnDefaultAuth.Show();
            picGMailLogin.Hide();
            picOutlook.Hide();
            picYahoo.Hide();
            wbrMain.Navigate(OutlookOAuth2Provider.BuildAuthenticationUri());
        }
        protected OidcClientBase(int portalId, AuthMode mode, string service)
        {
            _authMode = mode;
            _service  = service;

            _apiKey    = OidcConfigBase.GetConfig(_service, portalId).APIKey;
            _apiSecret = OidcConfigBase.GetConfig(_service, portalId).APISecret;

            _callbackUri = _authMode == AuthMode.Login
                                    ? Globals.LoginURL(string.Empty, false)
                                    : Globals.RegisterURL(string.Empty, string.Empty);
        }
        public Args()
        {
#if NETFRAMEWORK
            port        = Properties.Settings.Default.Port;
            clusterName = Properties.Settings.Default.ClusterName.Trim();
            user        = Properties.Settings.Default.User.Trim();
            password    = Properties.Settings.Default.Password.Trim();
            ns          = Properties.Settings.Default.Namespace.Trim();
            set         = Properties.Settings.Default.Set.Trim();
            authMode    = (AuthMode)Enum.Parse(typeof(AuthMode), Properties.Settings.Default.AuthMode.Trim(), true);

            if (Properties.Settings.Default.TlsEnable)
            {
                tlsName   = Properties.Settings.Default.TlsName.Trim();
                tlsPolicy = new TlsPolicy(
                    Properties.Settings.Default.TlsProtocols,
                    Properties.Settings.Default.TlsRevoke,
                    Properties.Settings.Default.TlsClientCertFile,
                    Properties.Settings.Default.TlsLoginOnly
                    );
            }

            hosts = Host.ParseHosts(Properties.Settings.Default.Host, tlsName, port);
#else
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("settings.json", optional: true, reloadOnChange: true);
            IConfigurationRoot section = builder.Build();

            port        = int.Parse(section.GetSection("Port").Value);
            clusterName = section.GetSection("ClusterName").Value;
            user        = section.GetSection("User").Value;
            password    = section.GetSection("Password").Value;
            ns          = section.GetSection("Namespace").Value;
            set         = section.GetSection("Set").Value;
            authMode    = (AuthMode)Enum.Parse(typeof(AuthMode), section.GetSection("AuthMode").Value, true);

            bool tlsEnable = bool.Parse(section.GetSection("TlsEnable").Value);

            if (tlsEnable)
            {
                tlsName   = section.GetSection("TlsName").Value;
                tlsPolicy = new TlsPolicy(
                    section.GetSection("TlsProtocols").Value,
                    section.GetSection("TlsRevoke").Value,
                    section.GetSection("TlsClientCertFile").Value,
                    bool.Parse(section.GetSection("TlsLoginOnly").Value)
                    );
            }

            hosts = Host.ParseHosts(section.GetSection("Host").Value, tlsName, port);
#endif
        }
示例#21
0
 public int GetAuthFlags(AuthMode mode)
 {
     //~ AuthFlags 4 = Anonymous Off, Impersonation On, Forms Off, Windows On
     if (mode == AuthMode.Windows)
     {
         return(4);
     }
     else
     {
         //~ AuthFlag 1 = Anonymous On, Impersonation On, Forms On, Windows Off
         return(1);
     }
 }
示例#22
0
        byte[] getRejsekortKeyByBlock(AuthMode authMode, int blockIndex)
        {
            int sectorId = getSectorIndexByBlockIndex(blockIndex);

            if (authMode == AuthMode.KEY_A)
            {
                return(callback.getKeyABySector(sectorId));
            }
            else
            {
                return(callback.getKeyBBySector(sectorId));
            }
        }
示例#23
0
        /// <summary>
        /// This document has some great explanations about how the auth mechanisms work on Mifare cards:
        /// http://www.metratec.com/fileadmin/docs/en/documentation/metraTec_MiFare_Protocol-Guide.pdf
        ///
        /// </summary>
        /// <returns>
        /// The auth.
        /// </returns>
        /// <param name='blockNo'>
        /// Block no.
        /// </param>
        /// <param name='authCode'>
        /// Auth code.
        /// </param>
        private MifareResponse sendAuth(byte blockNo, AuthMode authMode, byte[] authCode)
        {
            byte[] readBuffer  = new byte[64];
            int    offset      = 0;
            int    bytesToRead = 0;

            WriteCommand(Command.MIFARE_AUTHENTICATION2, NODE_BROADCAST,
                         new byte[] { (byte)authMode, blockNo }.Merge(authCode));

            // Naive busy way. Rewrite to consumer stream pull!
            do
            {
                Thread.Sleep(10);
                bytesToRead = port.BytesToRead;
            } while (bytesToRead == 0);

            // TODO: Use callback, make response parser able to read lazily from input stream
            int bytesRead = port.Read(readBuffer, offset, bytesToRead);

            // Evaluate data in buffer

            //Console.WriteLine ("Data received: {0} )", readBuffer.Subset(0,bytesRead).ToHex ());

            SelectResponse response = new SelectResponse();

            ushort length = readBuffer.Subset(2, 2).ToUInt16();
            //Console.WriteLine ("Length: {0} ( {1})", length, readBuffer.Subset (2, 2).ToHex ());

            ushort nodeID = readBuffer.Subset(4, 2).ToUInt16();

            //Console.WriteLine ("NodeID: {0} ( {1})", nodeID, readBuffer.Subset (4, 2).ToHex ());
            response.NodeId = nodeID;

            ushort commandCode = readBuffer.Subset(6, 2).ToUInt16();

            //Console.WriteLine ("Command: {0} ( {1})", Enum.GetName (typeof(CommandCode), commandCode), readBuffer.Subset (6, 2).ToHex ());
            response.Command = (Command)commandCode;

            byte responseCode = readBuffer[8];

            //Console.WriteLine ("Response Code: {0} ( {1})", Enum.GetName (typeof(ResponseCode), responseCode), responseCode.ToHex ());
            response.Response = (Response)responseCode;

            byte checksum = readBuffer[4 + length];

            byte calculatedChecksum = CalcCheckSum(readBuffer, 4, 4 + length);

            validateChecksum(checksum, calculatedChecksum);

            return(response);
        }
示例#24
0
        public LinkedInClient(int portalId, AuthMode mode) : base(portalId, mode, "LinkedIn")
        {
            AuthorizationEndpoint = new Uri("https://www.linkedin.com/uas/oauth/authorize");
            RequestTokenEndpoint = new Uri("https://api.linkedin.com/uas/oauth/requestToken");
            RequestTokenMethod = HttpMethod.POST;
            TokenEndpoint = new Uri("https://api.linkedin.com/uas/oauth/accessToken");
            MeGraphEndpoint = new Uri("http://api.linkedin.com/v1/people/~");

            AuthTokenName = "LinkedInUserToken";

            OAuthVersion = "1.0";

            LoadTokenCookie(String.Empty);
        }
        /// <summary>
        /// Logins the asynchronous.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="secret">The secret.</param>
        /// <param name="authMode">The authentication mode.</param>
        /// <returns></returns>
        /// <exception cref="WebServiceException">Unknown login mode: '{authMode}</exception>
        public async Task <bool> LoginAsync(string userName, string secret, AuthMode authMode = AuthMode.AccessKey)
        {
            switch (authMode)
            {
            case AuthMode.AccessKey:
                return(await Session.Login(userName, secret));

            case AuthMode.Password:
                return(await Session.LoginPassword(userName, secret));

            default:
                throw new WebServiceException($"Unknown login mode: '{authMode}'");
            }
        }
示例#26
0
        public LinkedInClient(int portalId, AuthMode mode) : base(portalId, mode, "LinkedIn")
        {
            AuthorizationEndpoint = new Uri("https://www.linkedin.com/uas/oauth/authorize");
            RequestTokenEndpoint  = new Uri("https://api.linkedin.com/uas/oauth/requestToken");
            RequestTokenMethod    = HttpMethod.POST;
            TokenEndpoint         = new Uri("https://api.linkedin.com/uas/oauth/accessToken");
            MeGraphEndpoint       = new Uri("http://api.linkedin.com/v1/people/~");

            AuthTokenName = "LinkedInUserToken";

            OAuthVersion = "1.0";

            LoadTokenCookie(String.Empty);
        }
示例#27
0
        public async Task UpdateOnlineAccountAsync(Account account, AuthMode authMode, string email,
                                                   AuthResult authResult,
                                                   string authServer = null)
        {
            account.AuthMode       = authMode;
            account.Email          = email;
            account.Username       = authResult.SelectedProfile.Name;
            account.UUID           = authResult.SelectedProfile.Id;
            account.ClientToken    = authResult.ClientToken;
            account.AccessToken    = authResult.AccessToken;
            account.AuthServerBase = authMode == AuthMode.AuthLibInjector ? authServer : null;

            await LoadSkinAsync(account);
        }
示例#28
0
        public LiveClient(int portalId, AuthMode mode) : base(portalId, mode, "Live")
        {
            TokenEndpoint         = new Uri("https://oauth.live.com/token");
            AuthorizationEndpoint = new Uri("https://oauth.live.com/authorize");
            MeGraphEndpoint       = new Uri("https://apis.live.net/v5.0/me");

            Scope = HttpContext.Current.Server.UrlEncode("wl.signin wl.basic wl.emails");

            AuthTokenName = "LiveUserToken";

            OAuthVersion = "2.0";

            LoadTokenCookie(String.Empty);
        }
示例#29
0
        public LiveClient(int portalId, AuthMode mode) : base(portalId, mode, "Live")
        {
            TokenEndpoint = new Uri("https://oauth.live.com/token");
            AuthorizationEndpoint = new Uri("https://oauth.live.com/authorize");
            MeGraphEndpoint = new Uri("https://apis.live.net/v5.0/me");

            Scope = HttpContext.Current.Server.UrlEncode("wl.signin wl.basic wl.emails");

            AuthTokenName = "LiveUserToken";

            OAuthVersion = "2.0";

            LoadTokenCookie(String.Empty);
        }
示例#30
0
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("authMode");
     writer.WriteStringValue(AuthMode.ToString());
     if (Optional.IsDefined(Description))
     {
         if (Description != null)
         {
             writer.WritePropertyName("description");
             writer.WriteStringValue(Description);
         }
         else
         {
             writer.WriteNull("description");
         }
     }
     if (Optional.IsDefined(Keys))
     {
         if (Keys != null)
         {
             writer.WritePropertyName("keys");
             writer.WriteObjectValue(Keys);
         }
         else
         {
             writer.WriteNull("keys");
         }
     }
     if (Optional.IsCollectionDefined(Properties))
     {
         if (Properties != null)
         {
             writer.WritePropertyName("properties");
             writer.WriteStartObject();
             foreach (var item in Properties)
             {
                 writer.WritePropertyName(item.Key);
                 writer.WriteStringValue(item.Value);
             }
             writer.WriteEndObject();
         }
         else
         {
             writer.WriteNull("properties");
         }
     }
     writer.WriteEndObject();
 }
示例#31
0
        public TwitterClient(int portalId, AuthMode mode)
            : base(portalId, mode, "Twitter")
        {
            AuthorizationEndpoint = new Uri("https://api.twitter.com/oauth/authorize");
            RequestTokenEndpoint  = new Uri("https://api.twitter.com/oauth/request_token");
            RequestTokenMethod    = HttpMethod.POST;
            TokenEndpoint         = new Uri("https://api.twitter.com/oauth/access_token");
            MeGraphEndpoint       = new Uri("https://api.twitter.com/1.1/account/verify_credentials.json");

            AuthTokenName = "TwitterUserToken";

            OAuthVersion = "1.0";

            LoadTokenCookie(String.Empty);
        }
示例#32
0
文件: AuthUtil.cs 项目: lowet84/when
        public static User Authorize(this UserContext context, AuthMode authMode = AuthMode.UserInDb)
        {
            if (context.UserName == null)
            {
                throw new AuthenticationException("Not authorized");
            }
            var user = context.GetCurrentUser(UserContext.ReadType.Shallow);

            if (user == null && authMode == AuthMode.UserInDb)
            {
                throw new AuthenticationException("No username set");
            }

            return(user);
        }
示例#33
0
        public TwitterClient(int portalId, AuthMode mode)
            : base(portalId, mode, "Twitter")
        {
            AuthorizationEndpoint = new Uri("https://api.twitter.com/oauth/authorize");
            RequestTokenEndpoint = new Uri("https://api.twitter.com/oauth/request_token");
            RequestTokenMethod = HttpMethod.POST;
            TokenEndpoint = new Uri("https://api.twitter.com/oauth/access_token");
            MeGraphEndpoint = new Uri("https://api.twitter.com/1/account/verify_credentials.json");

            AuthTokenName = "TwitterUserToken";

            OAuthVersion = "1.0";

            LoadTokenCookie(String.Empty);
        }
        private void ReadDefaults()
        {
            hostBox.Text                = Properties.Settings.Default.Host;
            portBox.Text                = Properties.Settings.Default.Port.ToString();
            clusterName                 = Properties.Settings.Default.ClusterName.Trim();
            nsBox.Text                  = Properties.Settings.Default.Namespace;
            setBox.Text                 = Properties.Settings.Default.Set;
            syncButton.Checked          = Properties.Settings.Default.Sync;
            asyncButton.Checked         = !syncButton.Checked;
            syncThreadBox.Text          = Properties.Settings.Default.SyncThreads.ToString();
            asyncThreadBox.Text         = Properties.Settings.Default.AsyncThreads.ToString();
            maxCommandBox.Text          = Properties.Settings.Default.AsyncMaxCommands.ToString();
            recordsBox.Text             = Properties.Settings.Default.Records.ToString();
            batchReadBox.Checked        = Properties.Settings.Default.BatchRead;
            batchSizeBox.Text           = Properties.Settings.Default.BatchSize.ToString();
            binTypeBox.SelectedIndex    = Properties.Settings.Default.BinType;
            binSizeBox.Text             = Properties.Settings.Default.BinSize.ToString();
            fixedValueButton.Checked    = Properties.Settings.Default.FixedValue;
            dynamicValueButton.Checked  = !fixedValueButton.Checked;
            initPctBox.Text             = Properties.Settings.Default.InitPct.ToString();
            readBox.Text                = Properties.Settings.Default.ReadPct.ToString();
            writeBox.Text               = Properties.Settings.Default.WritePct.ToString();
            timeoutBox.Text             = Properties.Settings.Default.Timeout.ToString();
            maxRetriesBox.Text          = Properties.Settings.Default.MaxRetries.ToString();
            sleepBox.Text               = Properties.Settings.Default.SleepBetweenRetries.ToString();
            replicaBox.SelectedIndex    = Properties.Settings.Default.Replica;
            latencyBox.Checked          = Properties.Settings.Default.Latency;
            latencyAltFormatBox.Checked = Properties.Settings.Default.LatencyAltFormat;
            latencyColumnsBox.Text      = Properties.Settings.Default.LatencyColumns.ToString();
            latencyShiftBox.Text        = Properties.Settings.Default.LatencyShift.ToString();
            debugBox.Checked            = Properties.Settings.Default.Debug;
            limitTpsBox.Checked         = Properties.Settings.Default.LimitTPS;
            throughputBox.Text          = Properties.Settings.Default.Throughput.ToString();
            authMode = (AuthMode)Enum.Parse(typeof(AuthMode), Properties.Settings.Default.AuthMode.Trim(), true);
            readModeAPBox.SelectedIndex = Properties.Settings.Default.ReadModeAP;
            readModeSCBox.SelectedIndex = Properties.Settings.Default.ReadModeSC;

            if (Properties.Settings.Default.TlsEnable)
            {
                tlsName   = Properties.Settings.Default.TlsName.Trim();
                tlsPolicy = new TlsPolicy(
                    Properties.Settings.Default.TlsProtocols,
                    Properties.Settings.Default.TlsRevoke,
                    Properties.Settings.Default.TlsClientCertFile,
                    Properties.Settings.Default.TlsLoginOnly
                    );
            }
        }
示例#35
0
        public GoogleClient(int portalId, AuthMode mode) 
            : base(portalId, mode, "Google")
        {
            TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token");
            TokenMethod = HttpMethod.POST;
            AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth");
            MeGraphEndpoint = new Uri("https://www.googleapis.com/oauth2/v1/userinfo");

            Scope = HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");

            AuthTokenName = "GoogleUserToken";

            OAuthVersion = "2.0";

            LoadTokenCookie(String.Empty);
        }
示例#36
0
        public FacebookClient(int portalId, AuthMode mode) 
            : base(portalId, mode, "Facebook")
        {
            TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token");
            TokenMethod = HttpMethod.GET;
            AuthorizationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize");
            MeGraphEndpoint = new Uri("https://graph.facebook.com/me");

            Scope = "email";

            AuthTokenName = "FacebookUserToken";

            OAuthVersion = "2.0";

            LoadTokenCookie(String.Empty);
        }
示例#37
0
        public LiveClient(int portalId, AuthMode mode) : base(portalId, mode, "Live")
        {
            //DNN-6464 Correct TokenEndpoint and AuthorizationEndpoint Urls
            // Add TokenMethod of Post to conform to other OAuth extensions
            TokenMethod = HttpMethod.POST;
            TokenEndpoint = new Uri("https://login.live.com/oauth20_token.srf");
            AuthorizationEndpoint = new Uri("https://login.live.com/oauth20_authorize.srf");
            MeGraphEndpoint = new Uri("https://apis.live.net/v5.0/me");

            Scope = HttpContext.Current.Server.UrlEncode("wl.signin wl.basic wl.emails");

            AuthTokenName = "LiveUserToken";

            OAuthVersion = "2.0";

            LoadTokenCookie(String.Empty);
        }
示例#38
0
        private void LoadFrom(SimpleConfig config)
        {
            try
            {
                configfilepath = config.config_loc;

                try
                {

                    string x = config.appSettings[IgnoreListKey];
                    if (!String.IsNullOrEmpty(x))
                        ignoreList.AddRange(x.Trim().Split('|'));
                }
                catch { }

                try
                {
                    _logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), config.appSettings[LogLevelKey]);
                }
                catch {
                    _logLevel = LogLevel.WARN;
                }

                try
                {
                    string x = config.appSettings[AuthModePasswordKey];

                    if (!String.IsNullOrEmpty(x))
                        password = x;
                }
                catch { }
                try
                {
                    string x = config.appSettings[AuthModeUsernameKey];

                    if (!String.IsNullOrEmpty(x))
                        username = x;
                }
                catch { }
                try
                {
                    string x = config.appSettings[AuthModePKIInfoKey];

                    if (!String.IsNullOrEmpty(x))
                        pkiinfo = x;
                }
                catch { }

                try
                {
                    string x = config.appSettings[DCSUrlKey];

                    if (!String.IsNullOrEmpty(x))
                        dcsurl.AddRange(x.Trim().Split('|'));
                }
                catch { }
                try
                {
                    string x = config.appSettings[SSUrlKey];

                    if (!String.IsNullOrEmpty(x))
                        ssurl.AddRange(x.Trim().Split('|'));
                }
                catch { }
                try
                {
                    string x = config.appSettings[PCSUrlKey];
                    if (!String.IsNullOrEmpty(x))
                        pcsurl.AddRange(x.Trim().Split('|'));
                }
                catch { }

                try
                {
                    DCSalgo = (Algorithm)Enum.Parse(typeof(Algorithm), config.appSettings[UddiFindTypekey]);
                }
                catch { }
                try
                {
                    DCSalgo = (Algorithm)Enum.Parse(typeof(Algorithm), config.appSettings[DCSlagokey]);
                }
                catch { }
                try
                {
                    PCSalgo = (Algorithm)Enum.Parse(typeof(Algorithm), config.appSettings[PCSlagokey]);
                }
                catch { }
                try
                {
                    authMode = (AuthMode)Enum.Parse(typeof(AuthMode), config.appSettings[AuthModeKey]);
                }
                catch { }
                try
                {
                    DeadMessageDuration = (long)long.Parse(config.appSettings[DeadMsgkey]);
                }
                catch { }
                try
                {
                    DependencyInjectionEnabled = (bool)bool.Parse(config.appSettings[DepInjkey]);
                }
                catch { }
                try
                {
                    UddiEnabled = (bool)bool.Parse(config.appSettings[UddiEnabledKey]);
                }
                catch { }

                try
                {
                    DNSEnabled = (bool)bool.Parse(config.appSettings[DNSEnabledKey]);
                }
                catch { }

                try
                {
                    ServiceUnavailableBehavior = (UnavailableBehavior)Enum.Parse(typeof(UnavailableBehavior), config.appSettings[AgentBevKey]);
                }
                catch { }
                try
                {
                    DCSretrycount = Int32.Parse(config.appSettings[DCSlretrykey]);
                }
                catch { }
                try
                {
                    PCSretrycount = Int32.Parse(config.appSettings[PCSlretrykey]);
                }
                catch { }
                try
                {
                    DiscoveryInterval = Int32.Parse(config.appSettings[discoveryInterval]);
                }
                catch { }
                try
                {
                    UddiInquiryUrl = (config.appSettings[UddiURLKey]);
                }
                catch { }
                try
                {
                    UddiSecurityUrl = (config.appSettings[UddiSecUrlKey]);
                }
                catch { }
                try
                {
                    UddiAuthRequired = bool.Parse(config.appSettings[UddiAuthKey]);
                }
                catch { }

                try
                {
                    UddiUsername = (config.appSettings[UddiUsernameKey]);
                }
                catch { }
                try
                {
                    UddiEncryptedPassword = (config.appSettings[UddipwdKey]);
                }
                catch { }
                try
                {
                    UddiDCSLookup = (config.appSettings[UddiDCSkey]);
                }
                catch { }
                try
                {
                    UddiPCSLookup = (config.appSettings[UddiPCSkey]);
                }
                catch { }
                try
                {
                    _uddifindType = (UddiFindType)Enum.Parse(typeof(UddiFindType), (config.appSettings[UddiFindTypekey]));
                }
                catch { }

                try
                {
                    operatingmode = (OperationMode)Enum.Parse(typeof(OperationMode), (config.appSettings[operatingModeKey]));
                }
                catch { }

                try
                {
                    PersistLocation = (config.appSettings[PersistKey]);
                }
                catch { }

            }
            catch (Exception)
            {

            }
        }
示例#39
0
 public static extern bool AddToWlanPreferredList([MarshalAs(UnmanagedType.LPWStr)]string szSSID, AuthMode authMode, EncryptMode encryptMode, [MarshalAs(UnmanagedType.LPWStr)]string szKey, EapType eapType, [MarshalAs(UnmanagedType.Bool)]bool bAdhoc);
示例#40
0
 /// <summary>
 /// Joins a wireless network
 /// </summary>
 /// <param name="SSID">The name of the wireless network</param>
 /// <param name="Channel">The channel the AP is listening on (0 for autodetect)</param>
 /// <param name="Authentication">The method for authentication</param>
 /// <param name="Key">The shared key required to join the network (WEP / WPA)</param>
 /// <param name="KeyIndex">The index of the key (WEP only)</param>
 public void JoinNetwork(string SSID, int Channel = 0, AuthMode Authentication = AuthMode.Open, string Key = "", int KeyIndex = 1)
 {
     // Enterring command mode
     this._CommandMode_Start();
     // Configures the network
     if (!this._CommandMode_Exec("set wlan ssid " + SSID)) throw new SystemException(this._CommandMode_Response);
     if (!this._CommandMode_Exec("set wlan channel " + Channel)) throw new SystemException(this._CommandMode_Response);
     if (!this._CommandMode_Exec("set wlan auth " + Authentication.ToString())) throw new SystemException(this._CommandMode_Response);
     if (Authentication == AuthMode.WEP_128)
     {
         if (!this._CommandMode_Exec("set wlan key " + Key)) throw new SystemException(this._CommandMode_Response);
         if (!this._CommandMode_Exec("set wlan num " + KeyIndex.ToString())) throw new SystemException(this._CommandMode_Response);
     }
     else if (Authentication != AuthMode.Open)
     {
         if (!this._CommandMode_Exec("set wlan phrase " + Key)) throw new SystemException(this._CommandMode_Response);
     }
     // Actually joins the network
     this._SerialPort_Write("join\r");
     // Closes down command mode
     this._CommandMode_Stop();
 }
示例#41
0
        public Patcher(string PatchList, string FilesPath, DownloadMode Mode = DownloadMode.HTTP, AuthMode Auth = AuthMode.NOAUTH)
        {
            this.PatchListPath = new Uri(PatchList);
            this.FilesPath = FilesPath;

            Authentication = Auth;

            if (Mode != DownloadMode.HTTP)
            {
                throw new NotImplementedException("FTP Downloading is not Supportet, yet.");
            }
        }
示例#42
0
        /// <summary>
        /// Joins a wireless network
        /// </summary>
        /// <param name="SSID">The name of the wireless network</param>
        /// <param name="Channel">The channel the AP is listening on (0 for autodetect)</param>
        /// <param name="Authentication">The method for authentication</param>
        /// <param name="Key">The shared key required to join the network (WEP / WPA)</param>
        /// <param name="KeyIndex">The index of the key (WEP only)</param>
        public bool JoinNetwork(string SSID, int Channel = 0, AuthMode Authentication = AuthMode.Open, string Key = "", int KeyIndex = 1)
        {
            // Enterring command mode
            this._CommandMode_Start();
            // Configures the network
            if (!this._CommandMode_Exec("set wlan ssid " + SSID)) throw new SystemException(this._CommandMode_Response);
            if (!this._CommandMode_Exec("set wlan channel " + Channel)) throw new SystemException(this._CommandMode_Response);
            if (!this._CommandMode_Exec("set wlan auth " + Authentication.ToString())) throw new SystemException(this._CommandMode_Response);
            if (Authentication == AuthMode.WEP_128)
            {
                if (!this._CommandMode_Exec("set wlan key " + Key)) throw new SystemException(this._CommandMode_Response);
                if (!this._CommandMode_Exec("set wlan num " + KeyIndex.ToString())) throw new SystemException(this._CommandMode_Response);
            }
            else if (Authentication != AuthMode.Open)
            {
                if (!this._CommandMode_Exec("set wlan phrase " + Key)) throw new SystemException(this._CommandMode_Response);
            }

            // Auto-Assoc Rightpoint chan=6 mode=MIXED SCAN OK\r\n
            // Auto-Assoc Rightpoint!! chan=6 mode=NONE FAILED\r\n
            var joinComplete = false;
            var joinSuccessful = false;
            var joinHandler = new Tools.StringEventHandler((text, time) =>
            {
                if (text.IndexOf("AUTH-ERR") >= 0)
                {
                    joinComplete = true;
                    joinSuccessful = false;
                    _DebugPrint('D', "Authentication error");
                }

                if (text.IndexOf("Auto-Assoc") >= 0 && text.IndexOf("NONE FAILED") >= 0)
                {
                    joinComplete = true;
                    joinSuccessful = false;
                    _DebugPrint('D', "Couldn't find network");
                }

                if (text.IndexOf("Associated!") >= 0)
                {
                    joinComplete = true;
                    joinSuccessful = true;
                }
            });

            // Actually joins the network
            this._lineRecieved += joinHandler;
            this._SerialPort_Write("join\r");

            for(var i =0; i< 40 && !joinComplete; i++)
            {
                Thread.Sleep(250);
            }

            this._lineRecieved -= joinHandler;

            // Closes down command mode
            this._CommandMode_Stop();

            return joinSuccessful;
        }