예제 #1
0
        /// <summary>
        /// 根据身份验证类型枚举获取已通过froms验证的同身份用户对象
        /// </summary>
        private object GetMemberByAuthenticationTypeAndTicket(AuthenticationType type, Dictionary <string, string> ticketDictionary)
        {
            Guid identityGuid;

            if (ticketDictionary.ContainsKey(type.ToString()) &&
                Guid.TryParse(ticketDictionary[type.ToString()], out identityGuid))
            {
                switch (type)
                {
                case AuthenticationType.Guest:
                    _cacheGuest = _guestService.GetGuestByGuid(identityGuid);
                    break;

                case AuthenticationType.Admin:
                    _cacheAdmin = _adminService.GetAdminByGuid(identityGuid);
                    break;

                case AuthenticationType.Customer:
                    _cacheCustomer = _customerService.GetCustomerByGuid(identityGuid);
                    break;

                default:
                    throw new ArgumentException(string.Format("Unsupported Authentication Type {0}", type));
                }
                return(GetCacheMemberByAuthenticationType(type));
            }
            return(null);
        }
예제 #2
0
    public static void MessageInspector_RoundtripCustomHeaders_ComplexType()
    {
        MI_ClientBase_ClientAuth mi_ClientBase_ClientAuth1 = null;
        MI_ClientBase_ClientAuth mi_ClientBase_ClientAuth2 = null;
        BasicHttpBinding         binding = null;
        string accessToken;

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding((BasicHttpSecurityMode)BasicHttpSecurityMode.None);
            AuthenticationType authType = AuthenticationType.Live;
            EndpointAddress    endPoint = new EndpointAddress(Endpoints.HttpBaseAddress_Basic);


            // *** EXECUTE FIRST VARIATION *** \\
            accessToken = "Not Allowed";
            mi_ClientBase_ClientAuth1 = new MI_ClientBase_ClientAuth(authType.ToString(), accessToken, binding, endPoint);
            ResultObject <string> result1 = mi_ClientBase_ClientAuth1.GetAuthToken();

            // *** EXECUTE SECOND VARIATION *** \\
            accessToken = "Allow";
            mi_ClientBase_ClientAuth2 = new MI_ClientBase_ClientAuth(authType.ToString(), accessToken, binding, endPoint);
            ResultObject <string> result2 = mi_ClientBase_ClientAuth2.GetAuthToken();

            // *** VALIDATE FIRST VARIATION *** \\
            string expectedErrorDescription = TestTypes.ResultMessage.GetErrorDescription(TestTypes.ErrorCode.UserNotAuthenticated);
            Assert.True(String.Equals(result1.Result, expectedErrorDescription), String.Format("Expected Error Description: {0}/Actual Error Description: {1}", expectedErrorDescription, result2.Result));
            TestTypes.ErrorCode returnedErrorCode = (TestTypes.ErrorCode)result1.ErrorCode;
            Assert.True(returnedErrorCode.Equals(TestTypes.ErrorCode.UserNotAuthenticated), String.Format("Expected Error Code: {0}/nActual Error Code: {1}", TestTypes.ErrorCode.UserNotAuthenticated, returnedErrorCode));
            Assert.True(result1.HttpStatusCode.Equals(System.Net.HttpStatusCode.Unauthorized), String.Format("Expected HttpStatusCode: {0}/nActual HttpStatusCode: {1}", System.Net.HttpStatusCode.Unauthorized, result2.HttpStatusCode));

            // *** VALIDATE SECOND VARIATION *** \\
            expectedErrorDescription = TestTypes.ResultMessage.GetErrorDescription(TestTypes.ErrorCode.Ok);
            Assert.True(String.Equals(result2.Result, expectedErrorDescription), String.Format("Expected Error Description: {0}/nActual Error Description: {1}", expectedErrorDescription, result2.Result));
            returnedErrorCode = (TestTypes.ErrorCode)result2.ErrorCode;
            Assert.True(returnedErrorCode.Equals(TestTypes.ErrorCode.Ok), String.Format("Expected Error Code: {0}/nActual Error Code: {1}", TestTypes.ErrorCode.Ok, returnedErrorCode));
            Assert.True(result2.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK), String.Format("Expected HttpStatusCode: {0}/nActual HttpStatusCode: {1}", System.Net.HttpStatusCode.OK, result2.HttpStatusCode));

            // *** CLEANUP *** \\
            ((ICommunicationObject)mi_ClientBase_ClientAuth1).Close();
            ((ICommunicationObject)mi_ClientBase_ClientAuth2).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)mi_ClientBase_ClientAuth1, (ICommunicationObject)mi_ClientBase_ClientAuth2);
        }
    }
예제 #3
0
        /// <summary>
        /// Attach a new identity to a parent app
        /// </summary>
        /// <param name="externalId">
        /// User ID
        /// </param>
        /// <param name="authenticationToken">
        /// Password or client side token
        /// </param>
        /// <param name="authenticationType">
        /// Type of authentication
        /// </param>
        /// <param name="externalAuthName">
        /// Optional - if using AuthenticationType of external
        /// </param>
        /// <param name="forceCreate">
        /// If the profile does not exist, should it be created?
        /// </param>
        /// <param name="success">
        /// The success callback.
        /// </param>
        /// <param name="failure">
        /// The failure callback.
        /// </param>
        /// <param name="cbObject">
        /// The user object sent to the callback.
        /// </param>
        public void AttachParentWithIdentity(
            string externalId,
            string authenticationToken,
            AuthenticationType authenticationType,
            string externalAuthName,
            bool forceCreate,
            SuccessCallback success = null,
            FailureCallback failure = null,
            object cbObject         = null)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data[OperationParam.IdentityServiceExternalId.Value] = externalId;
            data[OperationParam.AuthenticateServiceAuthenticateAuthenticationToken.Value] = authenticationToken;
            data[OperationParam.IdentityServiceAuthenticationType.Value] = authenticationType.ToString();

            if (Util.IsOptionalParameterValid(externalAuthName))
            {
                data[OperationParam.AuthenticateServiceAuthenticateExternalAuthName.Value] = externalAuthName;
            }

            data[OperationParam.AuthenticateServiceAuthenticateForceCreate.Value] = forceCreate;

            ServerCallback callback = BrainCloudClient.CreateServerCallback(success, failure, cbObject);
            ServerCall     sc       = new ServerCall(ServiceName.Identity, ServiceOperation.AttachParentWithIdentity, data, callback);

            m_brainCloudClientRef.SendRequest(sc);
        }
예제 #4
0
        public static void UpdateRecentServerList(string databaseName, string userName, string password, AuthenticationType authType)
        {
            try
            {
                userName = Cryptography.EncryptText(userName, ConnectionHelper.ConnectCryptoKey);
                password = Cryptography.EncryptText(password, ConnectionHelper.ConnectCryptoKey);
                string configFileFullPath  = Path.Combine(SqlBuildManager.Logging.Configure.AppDataPath, ConfigFileName);
                ServerConnectConfig config = new ServerConnectConfig();
                if (File.Exists(configFileFullPath))
                {
                    config.ReadXml(configFileFullPath);
                }

                DataRow[] row = config.ServerConfiguration.Select(config.ServerConfiguration.NameColumn.ColumnName + " ='" + databaseName + "'");
                if (row.Length == 0)
                {
                    config.ServerConfiguration.AddServerConfigurationRow(databaseName, DateTime.Now, userName, password, authType.ToString());
                }
                else
                {
                    var r = (ServerConnectConfig.ServerConfigurationRow)row[0];
                    r.LastAccessed       = DateTime.UtcNow;
                    r.UserName           = userName;
                    r.Password           = password;
                    r.AuthenticationType = authType.ToString();
                    r.AcceptChanges();
                }
                config.WriteXml(configFileFullPath);
            }
            catch (Exception exe)
            {
                log.LogError(exe, "Error updating Recent Server List");
            }
        }
        private static void InitializeUserClaims(
            AuthenticationType authenticationType,
            string email,
            IDictionary <string, string> additionalClaims,
            ClaimsIdentity identity)
        {
            SamlPocTraceListener.Log("SAML", $"AuthenticationService.InitializeUserClaims: Initialize claims of user {identity.Name}");

            identity.AddClaim(new Claim(nameof(AuthenticationType), authenticationType.ToString()));

            if (additionalClaims != null)
            {
                identity.AddClaims(additionalClaims.Select(attr => new Claim(attr.Key, attr.Value)));
            }

            // Check if user email is present in claims or attributes under a standard claim type
            if (!identity.HasClaim(c => c.Type == ClaimTypes.Email))
            {
                // Add email claim under a standard claim type
                identity.AddClaim(new Claim(ClaimTypes.Email, email));
            }

            SamlPocTraceListener.Log("SAML", $"AuthenticationService.InitializeUserClaims: Initialized claims of user {identity.Name}:\r\n" +
                                     Utils.SerializeToJson(identity.Claims.Select(c => new { c.Type, c.Value })));
        }
예제 #6
0
        /// <summary>
        ///     Crea la cabecera de autenticación
        /// </summary>
        /// <returns></returns>
        protected AuthenticationHeaderValue CreateAuthenticationHeader()
        {
            var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(String.Format("{0}:{1}", _accessKey, _secretKey)));
            var authenticationHeaderValue = new AuthenticationHeaderValue(_authenticationScheme.ToString(), token);

            return(authenticationHeaderValue);
        }
예제 #7
0
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("url");
     writer.WriteObjectValue(Url);
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     writer.WriteEndObject();
 }
예제 #8
0
        public virtual void SignOut(AuthenticationType type)
        {
            if (_httpContext?.Request == null ||
                !_httpContext.Request.IsAuthenticated ||
                !(_httpContext.User.Identity is FormsIdentity))
            {
                return;
            }

            var fromsIdentity    = (FormsIdentity)_httpContext.User.Identity;
            var ticketDictionary = StringToAuthenticationTicket(fromsIdentity.Ticket.UserData);

            if (ticketDictionary.ContainsKey(type.ToString()))
            {
                ticketDictionary.Remove(type.ToString());
            }

            //清除已缓存的已身份验证对象
            RemoveCacheMemberByAuthenticationType(type);
        }
예제 #9
0
 public void StoreValues(Data data, string path)
 {
     data.SetValue(@"" + path + @"AccountId", Data.EscapeString(AccountId));
     data.SetValue(@"" + path + @"AuthenticationType", AuthenticationType.ToString());
     data.SetValue(@"" + path + @"FtpConnectionType", FtpConnectionType.ToString());
     data.SetValue(@"" + path + @"KeyFileRequiresPass", KeyFileRequiresPass.ToString());
     data.SetValue(@"" + path + @"Password", _password);
     data.SetValue(@"" + path + @"PrivateKeyFile", Data.EscapeString(PrivateKeyFile));
     data.SetValue(@"" + path + @"Server", Data.EscapeString(Server));
     data.SetValue(@"" + path + @"UserName", Data.EscapeString(UserName));
 }
예제 #10
0
    public static void MessageInspector_RoundtripCustomHeaders()
    {
        MI_ClientBase_ClientAuth mi_ClientBase_ClientAuth = null;
        BasicHttpBinding         binding = null;
        string accessToken = "Allow";

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding((BasicHttpSecurityMode)BasicHttpSecurityMode.None);

            AuthenticationType authType = AuthenticationType.None;

            EndpointAddress endPoint = new EndpointAddress(Endpoints.HttpBaseAddress_Basic);

            mi_ClientBase_ClientAuth = new MI_ClientBase_ClientAuth(authType.ToString(), accessToken, binding, endPoint);

            // *** EXECUTE *** \\
            Dictionary <string, string> headers = mi_ClientBase_ClientAuth.ValidateHeaders();

            // *** VALIDATE *** \\
            string authorizationHeaderValue, authTypeHeaderValue = "";
            if (headers.TryGetValue("Authorization", out authorizationHeaderValue) && (headers.TryGetValue("authType", out authTypeHeaderValue)))
            {
                Assert.True(String.Equals(authorizationHeaderValue, accessToken), String.Format("Expected Authorization Header value: {0}/nActual Authorization Header value: {1}", accessToken, authorizationHeaderValue));
                Assert.True(String.Equals(authTypeHeaderValue, authType.ToString()), String.Format("Expected AuthType Header value: {0}/nActual AuthType Header value: {1}", authType.ToString(), authTypeHeaderValue));
            }
            else
            {
                Assert.True(false, String.Format("One or both of the expected headers were not found.\nHeader: \"authType\" had value: {0}\nHeader: \"HttpRequestHeader.Authorization\" had value: {1}", authorizationHeaderValue, authTypeHeaderValue));
            }

            // *** CLEANUP *** \\
            ((ICommunicationObject)mi_ClientBase_ClientAuth).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)mi_ClientBase_ClientAuth);
        }
    }
예제 #11
0
        private void DetachIdentity(string externalId, AuthenticationType authenticationType, bool continueAnon, SuccessCallback success, FailureCallback failure,
                                    object cbObject)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data[OperationParam.IdentityServiceExternalId.Value]         = externalId;
            data[OperationParam.IdentityServiceAuthenticationType.Value] = authenticationType.ToString();
            data[OperationParam.IdentityServiceConfirmAnonymous.Value]   = continueAnon;

            ServerCallback callback = BrainCloudClient.CreateServerCallback(success, failure, cbObject);
            ServerCall     sc       = new ServerCall(ServiceName.Identity, ServiceOperation.Detach, data, callback);

            m_brainCloudClientRef.SendRequest(sc);
        }
예제 #12
0
        private void MergeIdentity(string externalId, string authenticationToken, AuthenticationType authenticationType, SuccessCallback success, FailureCallback failure,
                                   object cbObject)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data[OperationParam.IdentityServiceExternalId.Value]         = externalId;
            data[OperationParam.IdentityServiceAuthenticationType.Value] = authenticationType.ToString();
            data[OperationParam.AuthenticateServiceAuthenticateAuthenticationToken.Value] = authenticationToken;

            ServerCallback callback = BrainCloudClient.CreateServerCallback(success, failure, cbObject);
            ServerCall     sc       = new ServerCall(ServiceName.Identity, ServiceOperation.Merge, data, callback);

            m_brainCloudClientRef.SendRequest(sc);
        }
예제 #13
0
 public void ExportTo(ConfigNode node)
 {
     node["ssh-host"]  = _sshHost;
     node["ssh-port"]  = _sshPort.ToString();
     node["account"]   = _sshAccount;
     node["auth-type"] = _authType.ToString();
     if (_authType == AuthenticationType.PublicKey)
     {
         node["keyfile"] = _privateKeyFile;
     }
     node["protocol"]    = _protocol.ToString();
     node["listen-port"] = _listenPort.ToString();
     node["dest-host"]   = _destinationHost;
     node["dest-port"]   = _destinationPort.ToString();
     node["allows-foreign-connection"] = _allowsForeignConnection.ToString();
     node["ipv6"] = _useIPv6.ToString();
 }
예제 #14
0
        public virtual void SignIn(Guid guid, AuthenticationType type, DateTime?expirantion = null, bool createPersistentCookie = true)
        {
            var now        = DateTime.UtcNow.ToLocalTime();
            var ticketName = _customerSettings.AuthenticationTicketName;
            var actualExpirationTimeSpan = expirantion.HasValue ?
                                           (expirantion.Value - now)
                : _expirationTimeSpan;

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                ticketName,
                now,
                now.Add(actualExpirationTimeSpan),
                createPersistentCookie,
                guid.ToString(),
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = _httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie == null)
            {
                cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
                {
                    HttpOnly = true
                };
                if (FormsAuthentication.CookieDomain != null)
                {
                    cookie.Domain = FormsAuthentication.CookieDomain;
                }
                if (ticket.IsPersistent)
                {
                    cookie.Expires = ticket.Expiration;
                }
                cookie.Secure = FormsAuthentication.RequireSSL;
                cookie.Path   = FormsAuthentication.FormsCookiePath;
            }

            var ticketDictionary = StringToAuthenticationTicket(cookie.Value);

            ticketDictionary[type.ToString().ToLower(CultureInfo.InvariantCulture)] = encryptedTicket;
            cookie.Value = AuthenticationTicketToString(ticketDictionary);

            _httpContext.Response.Cookies.Set(cookie);
        }
예제 #15
0
        /// <summary>
        /// Retrieves profile information of the specified user.
        /// </summary>
        /// <remarks>
        /// Service Name - Friend
        /// Service Operation - GET_PROFILE_INFO_FOR_CREDENTIAL
        /// </remarks>
        /// <param name="externalId">
        /// External id of the user to find
        /// </param>
        /// <param name="authenticationType">
        /// The authentication type used for the user's ID
        /// </param>
        /// <param name="success">
        /// The success callback.
        /// </param>
        /// <param name="failure">
        /// The failure callback.
        /// </param>
        /// <param name="cbObject">
        /// The user object sent to the callback.
        /// </param>
        public void GetProfileInfoForCredential(
            string externalId,
            AuthenticationType authenticationType,
            SuccessCallback success = null,
            FailureCallback failure = null,
            object cbObject         = null)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data[OperationParam.FriendServiceExternalId.Value]         = externalId;
            data[OperationParam.FriendServiceAuthenticationType.Value] = authenticationType.ToString();

            ServerCallback callback = BrainCloudClient.CreateServerCallback(success, failure, cbObject);
            ServerCall     sc       = new ServerCall(ServiceName.Friend, ServiceOperation.GetProfileInfoForCredential, data, callback);

            _client.SendRequest(sc);
        }
예제 #16
0
        public virtual void UpdateIISConfig(string configPath)
        {
            logger.Info(@"Server configuration file: {0}", configPath);
            logger.Info(@"Configuring server to: [http://localhost:{0}]", Port);

            var configXml = XDocument.Load(configPath);

            var bindings =
                configXml.XPathSelectElement("configuration/system.applicationHost/sites").Elements("site").Where(
                    d => d.Attribute("name").Value.ToLowerInvariant() == "nzbdrone").First().Element("bindings");

            bindings.Descendants().Remove();
            bindings.Add(
                new XElement("binding",
                             new XAttribute("protocol", "http"),
                             new XAttribute("bindingInformation", String.Format("*:{0}:localhost", Port))
                             ));

            bindings.Add(
                new XElement("binding",
                             new XAttribute("protocol", "http"),
                             new XAttribute("bindingInformation", String.Format("*:{0}:", Port))
                             ));

            //Update the authenticationTypes

            var location = configXml.XPathSelectElement("configuration").Elements("location").Where(
                d => d.Attribute("path").Value.ToLowerInvariant() == "nzbdrone").First();


            var authenticationTypes = location.XPathSelectElements("system.webServer/security/authentication").First().Descendants();

            //Set all authentication types enabled to false
            foreach (var child in authenticationTypes)
            {
                child.Attribute("enabled").Value = "false";
            }

            var configuredAuthType = String.Format("{0}Authentication", AuthenticationType.ToString()).ToLowerInvariant();

            //Set the users authenticationType to true
            authenticationTypes.Where(t => t.Name.ToString().ToLowerInvariant() == configuredAuthType).Single().Attribute("enabled").Value = "true";

            configXml.Save(configPath);
        }
        private static AuthenticationDetails GetAuthenticationDetails(AuthenticationType authenticationType, string userName, string password, byte[] content, string ppkPassword = null)
        {
            AuthenticationDetails authenticationDetails = new AuthenticationDetails();

            authenticationDetails.AuthenticationType = authenticationType.ToString();
            authenticationDetails.UserName           = userName;
            authenticationDetails.Password           = password;

            if (authenticationType == AuthenticationType.PrivateKey || authenticationType == AuthenticationType.MultiFactor)
            {
                authenticationDetails.Content         = Convert.ToBase64String(content);
                authenticationDetails.PpkFilePassword = ppkPassword;

                // Harcoding this, as this is used only in UX to display.
                authenticationDetails.PpkFileName = "DummyName.ppk";
            }

            return(authenticationDetails);
        }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(Type);
     if (Optional.IsDefined(ConnectVia))
     {
         writer.WritePropertyName("connectVia");
         writer.WriteObjectValue(ConnectVia);
     }
     if (Optional.IsDefined(Description))
     {
         writer.WritePropertyName("description");
         writer.WriteStringValue(Description);
     }
     if (Optional.IsCollectionDefined(Parameters))
     {
         writer.WritePropertyName("parameters");
         writer.WriteStartObject();
         foreach (var item in Parameters)
         {
             writer.WritePropertyName(item.Key);
             writer.WriteObjectValue(item.Value);
         }
         writer.WriteEndObject();
     }
     if (Optional.IsCollectionDefined(Annotations))
     {
         writer.WritePropertyName("annotations");
         writer.WriteStartArray();
         foreach (var item in Annotations)
         {
             writer.WriteObjectValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("typeProperties");
     writer.WriteStartObject();
     writer.WritePropertyName("host");
     writer.WriteObjectValue(Host);
     if (Optional.IsDefined(Port))
     {
         writer.WritePropertyName("port");
         writer.WriteObjectValue(Port);
     }
     if (Optional.IsDefined(HttpPath))
     {
         writer.WritePropertyName("httpPath");
         writer.WriteObjectValue(HttpPath);
     }
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     if (Optional.IsDefined(Username))
     {
         writer.WritePropertyName("username");
         writer.WriteObjectValue(Username);
     }
     if (Optional.IsDefined(Password))
     {
         writer.WritePropertyName("password");
         writer.WriteObjectValue(Password);
     }
     if (Optional.IsDefined(EnableSsl))
     {
         writer.WritePropertyName("enableSsl");
         writer.WriteObjectValue(EnableSsl);
     }
     if (Optional.IsDefined(TrustedCertPath))
     {
         writer.WritePropertyName("trustedCertPath");
         writer.WriteObjectValue(TrustedCertPath);
     }
     if (Optional.IsDefined(UseSystemTrustStore))
     {
         writer.WritePropertyName("useSystemTrustStore");
         writer.WriteObjectValue(UseSystemTrustStore);
     }
     if (Optional.IsDefined(AllowHostNameCNMismatch))
     {
         writer.WritePropertyName("allowHostNameCNMismatch");
         writer.WriteObjectValue(AllowHostNameCNMismatch);
     }
     if (Optional.IsDefined(AllowSelfSignedServerCert))
     {
         writer.WritePropertyName("allowSelfSignedServerCert");
         writer.WriteObjectValue(AllowSelfSignedServerCert);
     }
     if (Optional.IsDefined(EncryptedCredential))
     {
         writer.WritePropertyName("encryptedCredential");
         writer.WriteObjectValue(EncryptedCredential);
     }
     writer.WriteEndObject();
     foreach (var item in AdditionalProperties)
     {
         writer.WritePropertyName(item.Key);
         writer.WriteObjectValue(item.Value);
     }
     writer.WriteEndObject();
 }
예제 #19
0
 /// <summary>
 /// Used to know if a certain field is required for a certain AuthenticationType.
 /// </summary>
 /// <param name="field"></param>
 /// <param name="auth"></param>
 /// <returns>True if the field is required, false otherwise.</returns>
 public static bool RequiredFor(string field, AuthenticationType auth)
 {
     return(((List <string>) typeof(AuthenticationRequiredFields).GetField(auth.ToString()).GetValue(null)).Contains(field));
 }
예제 #20
0
        //ADD HERE NEW PROPERTIES (The property name must conform to the string value in AuthenticationType of the corresponding auth, and the list must contain at least 1 requried field)

        /// <summary>
        /// Returns the fields required to authenticate with a certain AuthenticationType.
        /// </summary>
        /// <param name="auth"></param>
        /// <returns>The list of required fields.</returns>
        public static List <string> Get(AuthenticationType auth)
        {
            return((List <string>) typeof(AuthenticationRequiredFields).GetField(auth.ToString(), BindingFlags.NonPublic | BindingFlags.Static).GetValue(null));
        }
예제 #21
0
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(Type);
     if (Optional.IsDefined(ConnectVia))
     {
         writer.WritePropertyName("connectVia");
         writer.WriteObjectValue(ConnectVia);
     }
     if (Optional.IsDefined(Description))
     {
         writer.WritePropertyName("description");
         writer.WriteStringValue(Description);
     }
     if (Optional.IsCollectionDefined(Parameters))
     {
         writer.WritePropertyName("parameters");
         writer.WriteStartObject();
         foreach (var item in Parameters)
         {
             writer.WritePropertyName(item.Key);
             writer.WriteObjectValue(item.Value);
         }
         writer.WriteEndObject();
     }
     if (Optional.IsCollectionDefined(Annotations))
     {
         writer.WritePropertyName("annotations");
         writer.WriteStartArray();
         foreach (var item in Annotations)
         {
             writer.WriteObjectValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("typeProperties");
     writer.WriteStartObject();
     writer.WritePropertyName("url");
     writer.WriteObjectValue(Url);
     if (Optional.IsDefined(EnableServerCertificateValidation))
     {
         writer.WritePropertyName("enableServerCertificateValidation");
         writer.WriteObjectValue(EnableServerCertificateValidation);
     }
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     if (Optional.IsDefined(UserName))
     {
         writer.WritePropertyName("userName");
         writer.WriteObjectValue(UserName);
     }
     if (Optional.IsDefined(Password))
     {
         writer.WritePropertyName("password");
         writer.WriteObjectValue(Password);
     }
     if (Optional.IsDefined(ServicePrincipalId))
     {
         writer.WritePropertyName("servicePrincipalId");
         writer.WriteObjectValue(ServicePrincipalId);
     }
     if (Optional.IsDefined(ServicePrincipalKey))
     {
         writer.WritePropertyName("servicePrincipalKey");
         writer.WriteObjectValue(ServicePrincipalKey);
     }
     if (Optional.IsDefined(Tenant))
     {
         writer.WritePropertyName("tenant");
         writer.WriteObjectValue(Tenant);
     }
     if (Optional.IsDefined(AadResourceId))
     {
         writer.WritePropertyName("aadResourceId");
         writer.WriteObjectValue(AadResourceId);
     }
     if (Optional.IsDefined(EncryptedCredential))
     {
         writer.WritePropertyName("encryptedCredential");
         writer.WriteObjectValue(EncryptedCredential);
     }
     writer.WriteEndObject();
     foreach (var item in AdditionalProperties)
     {
         writer.WritePropertyName(item.Key);
         writer.WriteObjectValue(item.Value);
     }
     writer.WriteEndObject();
 }
        private void Authenticate(
            string externalId,
            string authenticationToken,
            AuthenticationType authenticationType,
            string externalAuthName,
            bool forceCreate,
            SuccessCallback success = null,
            FailureCallback failure = null,
            object cbObject         = null)
        {
            string languageCode = _client.LanguageCode;
            double utcOffset    = Util.GetUTCOffsetForCurrentTimeZone();
            string countryCode  = _client.CountryCode;

            Dictionary <string, object> data = new Dictionary <string, object>();

            data[OperationParam.AuthenticateServiceAuthenticateExternalId.Value]          = externalId;
            data[OperationParam.AuthenticateServiceAuthenticateAuthenticationToken.Value] = authenticationToken;
            data[OperationParam.AuthenticateServiceAuthenticateAuthenticationType.Value]  = authenticationType.ToString();
            data[OperationParam.AuthenticateServiceAuthenticateForceCreate.Value]         = forceCreate;

            data[OperationParam.AuthenticateServiceAuthenticateProfileId.Value]         = ProfileId;
            data[OperationParam.AuthenticateServiceAuthenticateAnonymousId.Value]       = AnonymousId;
            data[OperationParam.AuthenticateServiceAuthenticateGameId.Value]            = _client.AppId;
            data[OperationParam.AuthenticateServiceAuthenticateReleasePlatform.Value]   = _client.ReleasePlatform.ToString();
            data[OperationParam.AuthenticateServiceAuthenticateGameVersion.Value]       = _client.AppVersion;
            data[OperationParam.AuthenticateServiceAuthenticateBrainCloudVersion.Value] = Version.GetVersion();

#if DOT_NET
            data["clientLib"] = "csharp";
#else
            data["clientLib"] = "csharp-unity";
#endif

            if (Util.IsOptionalParameterValid(externalAuthName))
            {
                data[OperationParam.AuthenticateServiceAuthenticateExternalAuthName.Value] = externalAuthName;
            }
            data[OperationParam.AuthenticateServiceAuthenticateCountryCode.Value]    = countryCode;
            data[OperationParam.AuthenticateServiceAuthenticateLanguageCode.Value]   = languageCode;
            data[OperationParam.AuthenticateServiceAuthenticateTimeZoneOffset.Value] = utcOffset;

            ServerCallback callback = BrainCloudClient.CreateServerCallback(success, failure, cbObject);
            ServerCall     sc       = new ServerCall(ServiceName.Authenticate, ServiceOperation.Authenticate, data, callback);
            _client.SendRequest(sc);
        }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(Type);
     if (Optional.IsDefined(ConnectVia))
     {
         writer.WritePropertyName("connectVia");
         writer.WriteObjectValue(ConnectVia);
     }
     if (Optional.IsDefined(Description))
     {
         writer.WritePropertyName("description");
         writer.WriteStringValue(Description);
     }
     if (Optional.IsCollectionDefined(Parameters))
     {
         writer.WritePropertyName("parameters");
         writer.WriteStartObject();
         foreach (var item in Parameters)
         {
             writer.WritePropertyName(item.Key);
             writer.WriteObjectValue(item.Value);
         }
         writer.WriteEndObject();
     }
     if (Optional.IsCollectionDefined(Annotations))
     {
         writer.WritePropertyName("annotations");
         writer.WriteStartArray();
         foreach (var item in Annotations)
         {
             writer.WriteObjectValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("typeProperties");
     writer.WriteStartObject();
     writer.WritePropertyName("deploymentType");
     writer.WriteStringValue(DeploymentType.ToString());
     if (Optional.IsDefined(HostName))
     {
         writer.WritePropertyName("hostName");
         writer.WriteObjectValue(HostName);
     }
     if (Optional.IsDefined(Port))
     {
         writer.WritePropertyName("port");
         writer.WriteObjectValue(Port);
     }
     if (Optional.IsDefined(ServiceUri))
     {
         writer.WritePropertyName("serviceUri");
         writer.WriteObjectValue(ServiceUri);
     }
     if (Optional.IsDefined(OrganizationName))
     {
         writer.WritePropertyName("organizationName");
         writer.WriteObjectValue(OrganizationName);
     }
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     if (Optional.IsDefined(Username))
     {
         writer.WritePropertyName("username");
         writer.WriteObjectValue(Username);
     }
     if (Optional.IsDefined(Password))
     {
         writer.WritePropertyName("password");
         writer.WriteObjectValue(Password);
     }
     if (Optional.IsDefined(ServicePrincipalId))
     {
         writer.WritePropertyName("servicePrincipalId");
         writer.WriteObjectValue(ServicePrincipalId);
     }
     if (Optional.IsDefined(ServicePrincipalCredentialType))
     {
         writer.WritePropertyName("servicePrincipalCredentialType");
         writer.WriteObjectValue(ServicePrincipalCredentialType);
     }
     if (Optional.IsDefined(ServicePrincipalCredential))
     {
         writer.WritePropertyName("servicePrincipalCredential");
         writer.WriteObjectValue(ServicePrincipalCredential);
     }
     if (Optional.IsDefined(EncryptedCredential))
     {
         writer.WritePropertyName("encryptedCredential");
         writer.WriteObjectValue(EncryptedCredential);
     }
     writer.WriteEndObject();
     foreach (var item in AdditionalProperties)
     {
         writer.WritePropertyName(item.Key);
         writer.WriteObjectValue(item.Value);
     }
     writer.WriteEndObject();
 }
예제 #24
0
        public virtual async Task <BaseResponse <TResponse> > GetData <TResponse>(string url, Dictionary <string, object> requestParams = null, string token = null)
        {
            BaseResponse <TResponse> result = new BaseResponse <TResponse>();

            try
            {
                if (requestParams != null)
                {
                    if (!url.Contains("?"))
                    {
                        url += "?";
                    }
                    foreach (KeyValuePair <string, object> k in requestParams)
                    {
                        url += $"{k.Key}={k.Value}&";
                    }
                    url = url.TrimEnd('&');
                }
                if (token != null)
                {
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(_authenticationType.ToString(), token);
                }

                HttpResponseMessage response = await httpClient.GetAsync(url);

                string responseData = await response.Content.ReadAsStringAsync();

                result.FullResponseString = responseData;

                if (response.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject <BaseResponse <TResponse> >(responseData);
                }
                else
                {
                    result.StatusCode = response.StatusCode;
                }
                result.FullResponseString = responseData;
            }
            catch (Exception ex)
            {
                result.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                result.Message    = ex.ToString();
            }
            return(result);
        }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(Type);
     if (ConnectVia != null)
     {
         writer.WritePropertyName("connectVia");
         writer.WriteObjectValue(ConnectVia);
     }
     if (Description != null)
     {
         writer.WritePropertyName("description");
         writer.WriteStringValue(Description);
     }
     if (Parameters != null)
     {
         writer.WritePropertyName("parameters");
         writer.WriteStartObject();
         foreach (var item in Parameters)
         {
             writer.WritePropertyName(item.Key);
             writer.WriteObjectValue(item.Value);
         }
         writer.WriteEndObject();
     }
     if (Annotations != null)
     {
         writer.WritePropertyName("annotations");
         writer.WriteStartArray();
         foreach (var item in Annotations)
         {
             writer.WriteObjectValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("typeProperties");
     writer.WriteStartObject();
     writer.WritePropertyName("host");
     writer.WriteObjectValue(Host);
     writer.WritePropertyName("port");
     writer.WriteObjectValue(Port);
     if (ServerType != null)
     {
         writer.WritePropertyName("serverType");
         writer.WriteStringValue(ServerType.Value.ToString());
     }
     if (ThriftTransportProtocol != null)
     {
         writer.WritePropertyName("thriftTransportProtocol");
         writer.WriteStringValue(ThriftTransportProtocol.Value.ToString());
     }
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     if (Username != null)
     {
         writer.WritePropertyName("username");
         writer.WriteObjectValue(Username);
     }
     if (Password != null)
     {
         writer.WritePropertyName("password");
         writer.WriteObjectValue(Password);
     }
     if (HttpPath != null)
     {
         writer.WritePropertyName("httpPath");
         writer.WriteObjectValue(HttpPath);
     }
     if (EnableSsl != null)
     {
         writer.WritePropertyName("enableSsl");
         writer.WriteObjectValue(EnableSsl);
     }
     if (TrustedCertPath != null)
     {
         writer.WritePropertyName("trustedCertPath");
         writer.WriteObjectValue(TrustedCertPath);
     }
     if (UseSystemTrustStore != null)
     {
         writer.WritePropertyName("useSystemTrustStore");
         writer.WriteObjectValue(UseSystemTrustStore);
     }
     if (AllowHostNameCNMismatch != null)
     {
         writer.WritePropertyName("allowHostNameCNMismatch");
         writer.WriteObjectValue(AllowHostNameCNMismatch);
     }
     if (AllowSelfSignedServerCert != null)
     {
         writer.WritePropertyName("allowSelfSignedServerCert");
         writer.WriteObjectValue(AllowSelfSignedServerCert);
     }
     if (EncryptedCredential != null)
     {
         writer.WritePropertyName("encryptedCredential");
         writer.WriteObjectValue(EncryptedCredential);
     }
     writer.WriteEndObject();
     foreach (var item in AdditionalProperties)
     {
         writer.WritePropertyName(item.Key);
         writer.WriteObjectValue(item.Value);
     }
     writer.WriteEndObject();
 }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(Type);
     if (Optional.IsDefined(ConnectVia))
     {
         writer.WritePropertyName("connectVia");
         writer.WriteObjectValue(ConnectVia);
     }
     if (Optional.IsDefined(Description))
     {
         writer.WritePropertyName("description");
         writer.WriteStringValue(Description);
     }
     if (Optional.IsCollectionDefined(Parameters))
     {
         writer.WritePropertyName("parameters");
         writer.WriteStartObject();
         foreach (var item in Parameters)
         {
             writer.WritePropertyName(item.Key);
             writer.WriteObjectValue(item.Value);
         }
         writer.WriteEndObject();
     }
     if (Optional.IsCollectionDefined(Annotations))
     {
         writer.WritePropertyName("annotations");
         writer.WriteStartArray();
         foreach (var item in Annotations)
         {
             writer.WriteObjectValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("typeProperties");
     writer.WriteStartObject();
     writer.WritePropertyName("endpoint");
     writer.WriteObjectValue(Endpoint);
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     if (Optional.IsDefined(Username))
     {
         writer.WritePropertyName("username");
         writer.WriteObjectValue(Username);
     }
     if (Optional.IsDefined(Password))
     {
         writer.WritePropertyName("password");
         writer.WriteObjectValue(Password);
     }
     if (Optional.IsDefined(ClientId))
     {
         writer.WritePropertyName("clientId");
         writer.WriteObjectValue(ClientId);
     }
     if (Optional.IsDefined(ClientSecret))
     {
         writer.WritePropertyName("clientSecret");
         writer.WriteObjectValue(ClientSecret);
     }
     if (Optional.IsDefined(UseEncryptedEndpoints))
     {
         writer.WritePropertyName("useEncryptedEndpoints");
         writer.WriteObjectValue(UseEncryptedEndpoints);
     }
     if (Optional.IsDefined(UseHostVerification))
     {
         writer.WritePropertyName("useHostVerification");
         writer.WriteObjectValue(UseHostVerification);
     }
     if (Optional.IsDefined(UsePeerVerification))
     {
         writer.WritePropertyName("usePeerVerification");
         writer.WriteObjectValue(UsePeerVerification);
     }
     if (Optional.IsDefined(EncryptedCredential))
     {
         writer.WritePropertyName("encryptedCredential");
         writer.WriteObjectValue(EncryptedCredential);
     }
     writer.WriteEndObject();
     foreach (var item in AdditionalProperties)
     {
         writer.WritePropertyName(item.Key);
         writer.WriteObjectValue(item.Value);
     }
     writer.WriteEndObject();
 }
예제 #27
0
        /// <summary>
        /// Handler for all message types.
        /// </summary>
        /// <remarks>
        /// Note we must not operate on the passed-in 'data' parameter after
        /// this routine returns, as it just references the receive buffer.
        /// </remarks>
        /// <param name="type">The message type.</param>
        /// <param name="data">The message data.</param>
        /// <returns>
        /// True if we entered send mode as a result of receiving this message,
        /// false if we're staying in receive mode and should re-start receive.
        /// </returns>
        private bool HandleMessage(MessageType type, ArraySegment <byte> data)
        {
#if DEBUG
            logger.Log(
                "HomeService Received '{0}' message with {1} bytes of data.",
                type.ToString(),
                data.Count.ToString());
#endif

            switch (type)
            {
            case MessageType.PadN:
                break;

            case MessageType.EchoRequest:
                this.bufferOffset = 0;
                this.AppendMessage(MessageType.EchoReply, data);
                this.SendMessage();
                return(true);

            case MessageType.EchoReply:
                break;

            case MessageType.Version:
                if (data.Count != sizeof(byte))
                {
                    this.ShutdownAndClose();
                    return(true);
                }

                this.peerProtocolVersion = data.Array[data.Offset];
#if DEBUG
                logger.Log(
                    " HomeService Server is using protocol version #{0}",
                    this.peerProtocolVersion.ToString());
#endif
                break;

            case MessageType.PleaseIdentify:
#if DEBUG
                logger.Log("  HomeService Sending Identification message");
#endif
                this.bufferOffset = 0;
                this.AppendMessage(
                    MessageType.Identification,
                    System.Text.Encoding.ASCII.GetBytes(this.identifier));
                this.SendMessage();
                return(true);

            case MessageType.PleaseAuthenticate:
                if (data.Count != sizeof(byte))
                {
                    this.ShutdownAndClose();
                    return(true);
                }

                AuthenticationType authType =
                    (AuthenticationType)data.Array[data.Offset];
#if DEBUG
                logger.Log(
                    "  HomeService Authentication request is for type {0}",
                    authType.ToString());
                logger.Log("  HomeService Sending SimpleAuthentication message");
#endif
                this.bufferOffset = 0;
                this.AppendMessage(
                    MessageType.SimpleAuthentication,
                    BitConverter.GetBytes(this.simpleAuthentication));
                this.SendMessage();
                return(true);

            case MessageType.Authenticated:
                this.bufferOffset = 0;
                if (this.clientToken == 0)
                {
#if DEBUG
                    logger.Log("  Sending RegisterService message");
#endif
                    this.AppendMessage(MessageType.RegisterService);
                }
                else
                {
#if DEBUG
                    logger.Log("  Sending ForwardToClient message");
#endif
                    this.AppendMessage(
                        MessageType.ForwardToClient,
                        BitConverter.GetBytes(this.clientToken));
                    this.forwarding = true;
                }

                this.SendMessage();
                return(true);

            case MessageType.ClientAwaits:
                if (data.Count != sizeof(uint))
                {
                    this.ShutdownAndClose();
                    return(true);
                }

                uint clientToken = BitConverter.ToUInt32(
                    data.Array,
                    data.Offset);
#if DEBUG
                logger.Log("  Client with instance token {0} awaits matchup.", clientToken.ToString());
                logger.Log("  Launching client connection to connect back in and match up with gatekeeper client instance.");
#endif

                // -
                // Note about garbage collection (GC).
                // The ServiceConnection constructor will have initiated
                // one or more async receive calls by the time it returns.
                // ReceiveAsync holds a reference to the
                // SocketAsyncEventArgs object in use, and that object
                // holds a reference to the ServiceConnection.  Everything
                // is driven off receive handlers, so some reference to the
                // new ServiceConnection should remain around until the
                // forwarding handler is invoked (or connection closed).
                // -
                Socket socket = StaticUtilities.CreateConnectedSocket(
                    this.socket.RemoteEndPoint);
                if (null != socket)
                {
                    ServiceConnection client = new ServiceConnection(
                        this.sslServerHost,
                        socket,
                        clientToken,
                        this.handler, this.logger);
                }
                break;

            default:
#if DEBUG
                logger.Log("  ** Unexpected message!  Closing! **");
#endif
                this.ShutdownAndClose();
                return(true);
            }

            return(false);
        }
예제 #28
0
 public void SetAuthenticationTypeOnServer(AuthenticationType authType, Action <PSServerMessage> endAction = null)
 {
     this.StartCoroutine(this.SetAuthenticationTypeOnServer(string.Format("{0}/UserService/SetAuthenticationType?authenticationType={1}&accessToken={2}&refreshToken={3}", (object)SingletonManager <Configuration> .Instance.SecureServerUrl, (object)authType.ToString(), (object)this.userLogin.accessToken, (object)this.refreshToken), authType, endAction));
 }
예제 #29
0
        public HttpResponse HandleAuthentication(TestContext ctx, HttpConnection connection, HttpRequest request,
                                                 out AuthenticationState state)
        {
            string authHeader;

            if (!request.Headers.TryGetValue(RequestAuthHeader, out authHeader))
            {
                authHeader = null;
            }

            if (AuthenticationType == AuthenticationType.ForceNone)
            {
                // Must not contain any auth header
                if (authHeader == null)
                {
                    state = AuthenticationState.None;
                    return(null);
                }
                state = AuthenticationState.Error;
                return(OnError("Must not contain any auth header."));
            }

            HttpResponse response;

            if (authHeader == null)
            {
                state    = AuthenticationState.Unauthenticated;
                response = OnUnauthenticated(ctx, connection, request, AuthenticationType.ToString());
                response.CloseConnection = true;
                return(response);
            }

            int pos  = authHeader.IndexOf(' ');
            var mode = authHeader.Substring(0, pos);
            var arg  = authHeader.Substring(pos + 1);

            if (!mode.Equals(AuthenticationType.ToString()))
            {
                state = AuthenticationState.Error;
                return(OnError("Invalid authentication scheme: {0}", mode));
            }

            if (mode.Equals("Basic"))
            {
                if (arg.Equals("eGFtYXJpbjptb25rZXk="))
                {
                    state = AuthenticationState.Authenticated;
                    return(null);
                }
                state = AuthenticationState.Error;
                return(OnError("Invalid Basic Authentication header"));
            }
            else if (!mode.Equals("NTLM"))
            {
                state = AuthenticationState.Error;
                return(OnError("Invalid authentication scheme: {0}", mode));
            }

            var bytes = Convert.FromBase64String(arg);

            if (!DependencyInjector.IsAvailable(typeof(NTLMHandler)))
            {
                state = AuthenticationState.Error;
                return(OnError("NTLM Support not available."));
            }

            var handler = DependencyInjector.Get <NTLMHandler> ();

            if (handler.HandleNTLM(ref bytes))
            {
                state = AuthenticationState.Authenticated;
                return(null);
            }

            state = AuthenticationState.Challenge;

            var token = "NTLM " + Convert.ToBase64String(bytes);

            response = OnUnauthenticated(ctx, connection, request, token);
            response.SetBody(new StringContent("I don't know you, who are you?"));
            return(response);
        }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     writer.WriteStringValue(Type);
     if (Optional.IsDefined(ConnectVia))
     {
         writer.WritePropertyName("connectVia");
         writer.WriteObjectValue(ConnectVia);
     }
     if (Optional.IsDefined(Description))
     {
         writer.WritePropertyName("description");
         writer.WriteStringValue(Description);
     }
     if (Optional.IsCollectionDefined(Parameters))
     {
         writer.WritePropertyName("parameters");
         writer.WriteStartObject();
         foreach (var item in Parameters)
         {
             writer.WritePropertyName(item.Key);
             writer.WriteObjectValue(item.Value);
         }
         writer.WriteEndObject();
     }
     if (Optional.IsCollectionDefined(Annotations))
     {
         writer.WritePropertyName("annotations");
         writer.WriteStartArray();
         foreach (var item in Annotations)
         {
             writer.WriteObjectValue(item);
         }
         writer.WriteEndArray();
     }
     writer.WritePropertyName("typeProperties");
     writer.WriteStartObject();
     writer.WritePropertyName("project");
     writer.WriteObjectValue(Project);
     if (Optional.IsDefined(AdditionalProjects))
     {
         writer.WritePropertyName("additionalProjects");
         writer.WriteObjectValue(AdditionalProjects);
     }
     if (Optional.IsDefined(RequestGoogleDriveScope))
     {
         writer.WritePropertyName("requestGoogleDriveScope");
         writer.WriteObjectValue(RequestGoogleDriveScope);
     }
     writer.WritePropertyName("authenticationType");
     writer.WriteStringValue(AuthenticationType.ToString());
     if (Optional.IsDefined(RefreshToken))
     {
         writer.WritePropertyName("refreshToken");
         writer.WriteObjectValue(RefreshToken);
     }
     if (Optional.IsDefined(ClientId))
     {
         writer.WritePropertyName("clientId");
         writer.WriteObjectValue(ClientId);
     }
     if (Optional.IsDefined(ClientSecret))
     {
         writer.WritePropertyName("clientSecret");
         writer.WriteObjectValue(ClientSecret);
     }
     if (Optional.IsDefined(Email))
     {
         writer.WritePropertyName("email");
         writer.WriteObjectValue(Email);
     }
     if (Optional.IsDefined(KeyFilePath))
     {
         writer.WritePropertyName("keyFilePath");
         writer.WriteObjectValue(KeyFilePath);
     }
     if (Optional.IsDefined(TrustedCertPath))
     {
         writer.WritePropertyName("trustedCertPath");
         writer.WriteObjectValue(TrustedCertPath);
     }
     if (Optional.IsDefined(UseSystemTrustStore))
     {
         writer.WritePropertyName("useSystemTrustStore");
         writer.WriteObjectValue(UseSystemTrustStore);
     }
     if (Optional.IsDefined(EncryptedCredential))
     {
         writer.WritePropertyName("encryptedCredential");
         writer.WriteObjectValue(EncryptedCredential);
     }
     writer.WriteEndObject();
     foreach (var item in AdditionalProperties)
     {
         writer.WritePropertyName(item.Key);
         writer.WriteObjectValue(item.Value);
     }
     writer.WriteEndObject();
 }
예제 #31
0
파일: Configurator.cs 프로젝트: 0anion0/IBN
        public void ChangeSqlServerSettings(string server, AuthenticationType authentication, string adminUser, string adminPassword, string portalUser, string portalPassword)
        {
            _sqlServer = server;
            _sqlAuthentication = authentication;
            _sqlAdminUser = adminUser;
            _sqlAdminPassword = adminPassword;
            _sqlPortalUser = portalUser;
            _sqlPortalPassword = portalPassword;

            RegistrySettings.WriteString(ConstSqlCommonServer, server);
            RegistrySettings.WriteString(ConstSqlCommonAuthentication, authentication.ToString());
            RegistrySettings.WriteString(ConstSqlCommonUser, adminUser);
            RegistrySettings.WriteString(ConstSqlCommonPassword, adminPassword);
            RegistrySettings.WriteString(ConstSqlPortalUser, portalUser);
            RegistrySettings.WriteString(ConstSqlPortalPassword, portalPassword);

            CreateDBHelper();
        }