Esempio n. 1
0
       public static PSObject Load(string target, CredentialType type = CredentialType.Generic)
       {
           PSObject cred;
           NativeMethods.CredRead(FixTarget(target), type, 0, out cred);

           return cred;
       }
        public ICredentials get_credentials_from_user(Uri uri, IWebProxy proxy, CredentialType credentialType)
        {
            if (!_config.Information.IsInteractive)
            {
                return CredentialCache.DefaultCredentials;
            }

            string message = credentialType == CredentialType.ProxyCredentials ?
                                 "Please provide proxy credentials:" :
                                 "Please provide credentials for: {0}".format_with(uri.OriginalString);
            this.Log().Info(ChocolateyLoggers.Important, message);

            Console.Write("User name: ");
            string username = Console.ReadLine();
            Console.Write("Password: ");
            var password = Console.ReadLine();

            //todo: set this up as secure
            //using (var securePassword = new SecureString())
            //{
            //    foreach (var letter in password.to_string())
            //    {
            //        securePassword.AppendChar(letter);
            //    }

            var credentials = new NetworkCredential
                {
                    UserName = username,
                    Password = password,
                    //SecurePassword = securePassword
                };
            return credentials;
            // }
        }
Esempio n. 3
0
 public Credential(CredentialType credentialType, string applicationName, string userName, string password)
 {
     ApplicationName = applicationName;
     UserName = userName;
     Password = password;
     CredentialType = credentialType;
 }
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            string message = credentialType == CredentialType.ProxyCredentials ?
                    LocalizedResourceManager.GetString("Credentials_ProxyCredentials") :
                    LocalizedResourceManager.GetString("Credentials_RequestCredentials");
            Console.WriteLine(message, uri.OriginalString);
            Console.Write(LocalizedResourceManager.GetString("Credentials_UserName"));
            string username = Console.ReadLine();
            Console.Write(LocalizedResourceManager.GetString("Credentials_Password"));

            using (SecureString password = new SecureString())
            {
                Console.ReadSecureString(password);
                var credentials = new NetworkCredential
                {
                    UserName = username,
                    SecurePassword = password
                };
                return credentials;
            }
        }
Esempio n. 5
0
 public Credential(CredentialType credentialType, string applicationName, string userName, string password)
 {
     _applicationName = applicationName;
     _userName = userName;
     _password = password;
     _credentialType = credentialType;
 }
        public static ICredentials CreateCredentials(
            CredentialType credentialType,
            String userName,
            String password,
            Uri url
        )
        {
            if (credentialType == CredentialType.Default
                && IsSharePointOnline(url)
            )
            {
                credentialType = CredentialType.SharePointOnline;
            }

            switch (credentialType)
            {
                case CredentialType.Windows:
                    return new NetworkCredential(
                        userName,
                        password
                    );
                case CredentialType.SharePointOnline:
                    return new SharePointOnlineCredentials(
                        userName,
                        password
                    );
            }

            return null;
        }
        public IHttpActionResult PutCredentialType(int id, CredentialType credentialType)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != credentialType.ID)
            {
                return BadRequest();
            }

            db.Entry(credentialType).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CredentialTypeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (LaunchedFromVS())
            {
                throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_CannotPromptForCedentials"));
            }

            string message = credentialType == CredentialType.ProxyCredentials ?
                    LocalizedResourceManager.GetString("Credentials_ProxyCredentials") :
                    LocalizedResourceManager.GetString("Credentials_RequestCredentials");
            Console.WriteLine(message, uri.OriginalString);
            Console.Write(LocalizedResourceManager.GetString("Credentials_UserName"));
            string username = Console.ReadLine();
            Console.Write(LocalizedResourceManager.GetString("Credentials_Password"));
            SecureString password = ReadLineAsSecureString();
            var credentials = new NetworkCredential
            {
                UserName = username,
                SecurePassword = password
            };

            return credentials;
        }
Esempio n. 9
0
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType , bool retrying)
        {
            if (Credentials.ContainsKey(uri))
                return Credentials[uri];

            return provider.GetCredentials(uri, proxy, credentialType, retrying);
        }
		public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
		{
			var cp = MonoDevelop.Core.WebRequestHelper.CredentialProvider;
			if (cp == null)
				return null;

			return cp.GetCredentials (uri, proxy, (MonoDevelop.Core.Web.CredentialType)credentialType, retrying);
		}
		internal PlaceholderForm (CredentialType type, Uri uri, NetworkCredential currentCredential)
		{
			this.uri = uri;
			this.type = type;
			current = currentCredential;
			Size = new Size (0, 0);
			Visible = false;
		}
		public ICredentials GetCredentials (Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
		{
			if (uri == null)
				throw new ArgumentNullException ("uri");

			var form = new PlaceholderForm (credentialType, uri, null);
			var result = GdkWin32.RunModalWin32Form (form, IdeApp.Workbench.RootWindow);
			return result ? new NetworkCredential (form.Username, form.Password, form.Domain) : null;
		}
Esempio n. 13
0
 public Credential(string username, string password, string target, CredentialType type)
 {
     Username = username;
     Password = password;
     Target = target;
     Type = type;
     PersistanceType = PersistanceType.Session;
     _lastWriteTime = DateTime.MinValue;
 }
		static ICredentials GetExistingCredentials (Uri uri, CredentialType credentialType)
		{
			var rootUri = new Uri (uri.GetComponents (UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
			var existing =
				PasswordService.GetWebUserNameAndPassword (uri) ??
				PasswordService.GetWebUserNameAndPassword (rootUri);

			return existing != null ? new NetworkCredential (existing.Item1, existing.Item2) : null;
		}
 public CredentialTypeViewModel Build(CredentialType credentialType)
 {
     return new CredentialTypeViewModel()
       {
     Id = credentialType.Id,
     Name = credentialType.Name,
     Position = credentialType.Position
       };
 }
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            return PromptUserForCredentials(uri, forcePrompt: true);
        }
		public ICredentials GetCredentials (Uri uri, IWebProxy proxy, CredentialType credentialType, ICredentials existingCredentials, bool retrying)
		{
			bool result = false;
			DispatchService.GuiSyncDispatch (() => {
				using (var ns = new NSAutoreleasePool ()) {
					var message = string.Format ("{0} needs {1} credentials to access {2}.", BrandingService.ApplicationName, 
					                             credentialType == CredentialType.ProxyCredentials ? "proxy" : "request", uri.Host);

					NSAlert alert = NSAlert.WithMessage ("Credentials Required", "OK", "Cancel", null, message);
					alert.Icon = NSApplication.SharedApplication.ApplicationIconImage;

					NSView view = new NSView (new RectangleF (0, 0, 313, 91));

					var creds = Utility.GetCredentialsForUriFromICredentials (uri, existingCredentials);

					var usernameLabel = new NSTextField (new RectangleF (17, 55, 71, 17)) {
						Identifier = "usernameLabel",
						StringValue = "Username:"******"Password:",
						Alignment = NSTextAlignment.Right,
						Editable = false,
						Bordered = false,
						DrawsBackground = false,
						Bezeled = false,
						Selectable = false,
					};
					view.AddSubview (passwordLabel);

					var passwordInput = new NSSecureTextField (new RectangleF (93, 20, 200, 22));
					passwordInput.StringValue = creds != null ? creds.Password : string.Empty;
					view.AddSubview (passwordInput);

					alert.AccessoryView = view;
					result = alert.RunModal () == 1;

					username = usernameInput.StringValue;
					password = passwordInput.StringValue;
				}
			});

			return result ? new NetworkCredential (username, password) : null;
		}
Esempio n. 18
0
 public AdalClient(
     AppConfig appConfig, 
     CredentialType credentialType, 
     IServiceInfoProvider serviceProvider = null)
     : base(appConfig, credentialType, serviceProvider)
 {
     appConfig.ServiceResource = Constants.Authentication.GraphServiceUrl;
     serviceProvider = new ServiceProvider();
     this.ServiceInformation = _serviceInfoProvider.CreateServiceInfo(appConfig, credentialType).Result;
 }
 public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
 {
     NetworkCredential credentials;
     // If we are retrying, the stored credentials must be invalid. 
     if (!retrying && (credentialType == CredentialType.RequestCredentials) && TryGetCredentials(out credentials))
     {
         return credentials;
     }
     return null;
 }
 public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
 {
     NetworkCredential credentials;
     // If we are retrying, the stored credentials must be invalid. 
     if (!retrying && (credentialType == CredentialType.RequestCredentials) && TryGetCredentials(uri, out credentials))
     {
         _logger.Log(MessageLevel.Info, NuGetResources.SettingsCredentials_UsingSavedCredentials, credentials.UserName);
         return credentials;
     }
     return _credentialProvider.GetCredentials(uri, proxy, credentialType, retrying);
 }
        public IHttpActionResult PostCredentialType(CredentialType credentialType)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.CredentialTypes.Add(credentialType);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = credentialType.ID }, credentialType);
        }
Esempio n. 22
0
		public void Add (Uri requestUri, ICredentials credentials, CredentialType credentialType)
		{
			credentialCache.TryAdd (requestUri, credentials);
			if (credentialType == CredentialType.RequestCredentials) {
				var rootUri = GetRootUri (requestUri);
				credentialCache.AddOrUpdate (rootUri, credentials, (u, c) => credentials);
			}

			var cred = Utility.GetCredentialsForUriFromICredentials (requestUri, credentials);
			if (cred != null && !string.IsNullOrWhiteSpace (cred.UserName) && !string.IsNullOrWhiteSpace (cred.Password))
				PasswordService.AddWebUserNameAndPassword (requestUri, cred.UserName, cred.Password);
		}
 public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
 {
     if (credentialType == CredentialType.RequestCredentials)
     {
         var dialog = new CredentialsDialog(uri.ToString(), "Connecting to " + uri.Host + "...", "Please provide credentials to connect to " + uri);
         if (dialog.Show() == DialogResult.OK)
         {
             return new NetworkCredential(dialog.Username, dialog.Password);
         }
     }
     return null;
 }
Esempio n. 24
0
        internal Subscription(WindowsAzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            this.SubscriptionName = azureSubscription.SubscriptionName;
            this.SubscriptionId = azureSubscription.SubscriptionId;
            this.ServiceEndpoint = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", azureSubscription.ServiceEndpoint.ToString().TrimEnd(new[]{'/'}), SubscriptionId));
            this.Certificate = azureSubscription.Certificate;
            this.CredentialType = CredentialType.UseCertificate;
        }
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
        {
            // Note: this might cause deadlock, but NuGet is sync while we need async, so keep it this way
            var credentialsTask = _authenticationProvider.GetCredentialsAsync(uri, retrying);
            var credentials = credentialsTask.Result;

            if (credentials == null || (string.IsNullOrWhiteSpace(credentials.UserName) && string.IsNullOrWhiteSpace(credentials.Password)))
            {
                return null;
            }

            return new NetworkCredential(credentials.UserName, credentials.Password);
        }
Esempio n. 26
0
		public ICredentials GetCredentials (Uri uri, CredentialType credentialType)
		{
			ICredentials credentials;
			if (!credentialCache.TryGetValue (uri, out credentials)) {
				if (credentialType == CredentialType.RequestCredentials &&
				    credentialCache.TryGetValue (GetRootUri (uri), out credentials))
					return credentials;
			} else {
				return credentials;
			}

			// Then go to the keychain
			var creds = PasswordService.GetWebUserNameAndPassword (uri);
			return creds != null ? new NetworkCredential (creds.Item1, creds.Item2).AsCredentialCache (uri) : null;
		}
		static ICredentials GetExistingCredentials (Uri uri, CredentialType credentialType)
		{
			if (credentialType == CredentialType.ProxyCredentials) {
				var proxyCreds = GetSystemProxyCredentials (uri);
				if (proxyCreds != null)
					return proxyCreds;
			}

			var rootUri = new Uri (uri.GetComponents (UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
			var existing =
				Keychain.FindInternetUserNameAndPassword (uri) ??
				Keychain.FindInternetUserNameAndPassword (rootUri);

			return existing != null ? new NetworkCredential (existing.Item1, existing.Item2) : null;
		}
Esempio n. 28
0
        internal Subscription(AzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            ProfileClient client = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            var environment = client.GetEnvironmentOrDefault(azureSubscription.Environment);

            this.SubscriptionName = azureSubscription.Name;
            this.SubscriptionId = azureSubscription.Id.ToString();
            this.ServiceEndpoint = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement).TrimEnd(new[] { '/' }), SubscriptionId));
            this.Certificate = FileUtilities.DataStore.GetCertificate(azureSubscription.Account);
            this.CredentialType = CredentialType.UseCertificate;
        }
		static ICredentials GetCredentialsFromUser (Uri uri, IWebProxy proxy, CredentialType credentialType)
		{
			NetworkCredential result = null;

			Runtime.RunInMainThread (() => {
				var form = new PlaceholderForm (credentialType, uri, null);
				if (GdkWin32.RunModalWin32Form (form, IdeApp.Workbench.RootWindow))
					result = new NetworkCredential (form.Username, form.Password, form.Domain);
			}).Wait ();

			// store the obtained credentials in the auth store
			// but don't store for the root url since it may have other credentials
			if (result != null)
				PasswordService.AddWebUserNameAndPassword (uri, result.UserName, result.Password);

			return result;
		}
        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
        {
            var url = Canonicalize(uri);
            var retry = Retries.GetOrAdd(url, _ => new RetryTracker());

            if (!retrying)
            {
                retry.Reset();
            }
            else
            {
                var retryAllowed = retry.AttemptRetry();
                if (!retryAllowed)
                    return null;
            }

            return new DynamicCachedCredential(url);
        }
Esempio n. 31
0
 static extern bool CredRead(string target, CredentialType type, int reservedFlag, out IntPtr credentialPtr);
Esempio n. 32
0
        public static void ExportCredentialPtr(IntPtr nCredPtr)
        {
            using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
            {
                CREDENTIAL     cred       = critCred.GetCredential();
                uint           Flags      = cred.Flags;
                CredentialType Type       = cred.Type;
                string         TargetName = Marshal.PtrToStringUni(cred.TargetName);
                string         Comment    = Marshal.PtrToStringUni(cred.Comment);
                System.Runtime.InteropServices.ComTypes.FILETIME LastWritten = cred.LastWritten;
                uint CredentialBlobSize = cred.CredentialBlobSize;
                var  data = new byte[CredentialBlobSize];

                if (CredentialBlobSize > 0)
                {
                    Marshal.Copy(cred.CredentialBlob, data, 0, data.Length);
                }
                uint Persist        = cred.Persist;
                int  AttributeCount = cred.AttributeCount;


                var attribSize = Marshal.SizeOf(typeof(NativeCredentialAttribute));


                ExportAttrib[] attribs = new ExportAttrib[AttributeCount];
                if (AttributeCount > 0)
                {
                    byte[] rawData = new byte[AttributeCount * attribSize];
                    var    buffer  = Marshal.AllocHGlobal(attribSize);
                    Marshal.Copy(cred.Attributes, rawData, (int)0, (int)AttributeCount * attribSize);



                    for (int i = 0; i < AttributeCount; i++)
                    {
                        Marshal.Copy(rawData, i * attribSize, buffer, attribSize);
                        var attr = (NativeCredentialAttribute)Marshal.PtrToStructure(buffer,
                                                                                     typeof(NativeCredentialAttribute));
                        var key = attr.Keyword;
                        var val = new byte[attr.ValueSize];
                        Marshal.Copy(attr.Value, val, (int)0, (int)attr.ValueSize);
                        Console.WriteLine("[-] Attribute {0}", key);

                        ExportAttrib attrib = new ExportAttrib();
                        attrib.Keyword   = attr.Keyword;
                        attrib.Flags     = attr.Flags;
                        attrib.ValueSize = attr.ValueSize;
                        attrib.Value     = val;

                        attribs[i] = attrib;
                    }
                }

                string TargetAlias = Marshal.PtrToStringUni(cred.TargetAlias);
                string UserName    = Marshal.PtrToStringUni(cred.UserName);

                ExportCred export = new ExportCred();
                export.Flags              = Flags;
                export.Type               = Type;
                export.TargetName         = TargetName;
                export.Comment            = Comment;
                export.LastWritten        = LastWritten;
                export.CredentialBlobSize = CredentialBlobSize;
                export.CredentialBlob     = data;
                export.Persist            = Persist;
                export.AttributeCount     = AttributeCount;
                export.AttributesLength   = AttributeCount * attribSize;
                export.Attributes         = attribs;
                export.TargetAlias        = TargetAlias;
                export.UserName           = UserName;

                Console.WriteLine(JsonConvert.SerializeObject(export).Replace("\"", "'"));
            }
        }
Esempio n. 33
0
 internal static string CredentialCacheKey(CredentialType credentialType, string identifier)
 {
     return("credential_" + credentialType.Id + "_" + identifier);
 }
Esempio n. 34
0
 static extern bool CredReadW([In] string target, [In] CredentialType type, [In] int reservedFlag, out IntPtr credentialPtr);
Esempio n. 35
0
 public static extern bool CredRead(string target, CredentialType type, int reservedFlag, out CredentialSafeHandle credentialPtr);
Esempio n. 36
0
        /// <summary>
        /// The Main method.
        /// </summary>
        /// <param name="args">Not used.</param>
        static int Main(string[] args)
        {
            startTime.Start();

            // Return codes.
            const int SUCCESS = 0;
            const int FAILURE = 1;

            int returnCode = SUCCESS;

            // Hostname to use when connecting to web service. Must contain the fully qualified domain name.
            String bwsHostname = "<bwsHostname>"; // e.g. bwsHostname = "server01.example.net"

            // Port to use when connecting to web service. The same port is used to access the
            // webconsole prior to BES12/UEM
            String bwsPort = "<bwsPort>"; // e.g. bwsPort = "18084"

            // Credeitnal type used in the authentication process
            CredentialType credentialType = new CredentialType();

            credentialType.PASSWORD = true;
            credentialType.value    = "PASSWORD";

            /*
             * BWS Host certificate must be installed on the client machine before running this sample code, otherwise
             * a SSL/TLS secure channel error will be thrown. For more information, see the BlackBerry Web Services
             * for Enterprise Administration For Microsoft .NET Developers Getting Started Guide.
             *
             * To test authentication populate the methods below with the appropriate credentials and
             * information
             */

            // Select which authentication methods you would like to test by setting the variables to true
            bool useAD   = true; // Active Directory
            bool useLDAP = true; // LDAP

            try
            {
                if (bwsHostname.IndexOf('.') < 1)
                {
                    throw new Exception(
                              "Invalid bwsHostname format. Expected format is \"server01.example.net\"");
                }
                // bwsPort, if not null, must be a positive integer
                if (bwsPort != null)
                {
                    int port = Int32.Parse(bwsPort);

                    if (port < 1)
                    {
                        throw new Exception("Invalid bwsPort. Expecting a positive integer string or null");
                    }
                }

                returnCode = (demonstrateBlackBerryAdministrationServiceAuthentication(bwsHostname,
                                                                                       bwsPort, credentialType)) ? SUCCESS : FAILURE;
                logMessage("");

                if (useAD && returnCode == SUCCESS)
                {
                    returnCode = (demonstrateActiveDirectoryAuthentication(bwsHostname, bwsPort,
                                                                           credentialType)) ? SUCCESS : FAILURE;
                    logMessage("");
                }
                if (useLDAP && returnCode == SUCCESS)
                {
                    returnCode = (demonstrateLDAPAuthentication(bwsHostname, bwsPort, credentialType))
                        ? SUCCESS : FAILURE;
                    logMessage("");
                }
            }
            catch (Exception e)
            {
                logMessage("Exception: \"{0}\"\n", e.Message);
                returnCode = FAILURE;
            }

            Console.Error.WriteLine("Exiting sample.\nPress Enter to exit\n");
            Console.ReadKey();

            return(returnCode);
        }
Esempio n. 37
0
        /// <summary>
        /// Demonstrates BlackBerry Administration Service Authentication. Fields denoted by "<value>"
        /// must be manually set.
        /// </summary>
        ///
        /// <returns>Returns true if authenticated successfully, false otherwise.</returns>
        private static bool demonstrateBlackBerryAdministrationServiceAuthentication(String bwsHostname,
                                                                                     String bwsPort, CredentialType credentialType)
        {
            logMessage("Attempting BlackBerry Administration Service authentication");

            // The BlackBerry Administration Service Credentials to use
            String username = "******"; // e.g. username = "******".
            String password = "******"; // e.g. password = "******".

            String authenticatorName = "BlackBerry Administration Service";
            String domain            = null; // not needed

            return(demonstrateBwsSetupAndAuthenticatedCall(bwsHostname, bwsPort, username, password,
                                                           domain, authenticatorName, credentialType));
        }
        private AuthConfig GetAuthConfig(RepositoryCredentialDescription credentials, string imageName, CredentialType credentialType)
        {
            var    authConfig = new AuthConfig();
            string username   = "";
            string password   = "";

            if (credentialType == CredentialType.TokenCredentials)
            {
                // Docker knows to do token authentication if the user name is a GUID of all zeroes
                username = Guid.Empty.ToString();

                if (!string.IsNullOrEmpty(cachedToken))
                {
                    password = cachedToken;
                }
                else if (!string.IsNullOrEmpty(HostingConfig.Config.ContainerRepositoryCredentialTokenEndPoint))
                {
                    if (HostingConfig.Config.ContainerRepositoryCredentialTokenEndPoint.Contains(HostingConfig.Config.DefaultMSIEndpointForTokenAuthentication))
                    {
                        // They are using Azure Container Registry
                        // get a refresh token from the azure container registry via MSI
                        password = GetRefreshTokenMSI(imageName);
                    }
                    else
                    {
                        password = GetGenericRefreshToken();
                    }
                }
                else
                {
                    // no container endpoint specified, try MSI
                    password = GetRefreshTokenMSI(imageName);
                }
            }
            else if (credentialType == CredentialType.AppManifestCredentials)
            {
                username = credentials.AccountName;

                bool isencrypted = (credentials.IsPasswordEncrypted || credentials.Type.Equals(Type.Encrypted));

                if (isencrypted && !string.IsNullOrEmpty(credentials.Password))
                {
                    password = Utility.GetDecryptedValue(credentials.Password);
                }
                else
                {
                    password = credentials.Password;
                }
            }
            else if (credentialType == CredentialType.ClusterManifestDefaultCredentials)
            {
                username = HostingConfig.Config.DefaultContainerRepositoryAccountName;

                bool isencrypted = (HostingConfig.Config.IsDefaultContainerRepositoryPasswordEncrypted || HostingConfig.Config.DefaultContainerRepositoryPasswordType.Equals(Type.Encrypted));

                if (isencrypted && !string.IsNullOrEmpty(HostingConfig.Config.DefaultContainerRepositoryPassword))
                {
                    password = Utility.GetDecryptedValue(HostingConfig.Config.DefaultContainerRepositoryPassword);
                }
                else
                {
                    password = HostingConfig.Config.DefaultContainerRepositoryPassword;
                }
            }

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                authConfig.Username = username;
                authConfig.Password = password;
                authConfig.Email    = credentials.Email;
            }

            return(authConfig);
        }
Esempio n. 39
0
 static extern bool CredDeleteW([In] string target, [In] CredentialType type, [In] int reservedFlag);
Esempio n. 40
0
 internal void SetNetworkCredentials(string userName, SecureString password)
 {
     this.CredentialType = CredentialType.NetworkCredential;
     this.userName       = userName;
     this.password       = password;
 }
Esempio n. 41
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="connection">info of connection</param>
 /// <param name="credentialType">choose one type to credential</param>
 public SMTPClientSending(SMTPServerConnection connection, CredentialType credentialType)
 {
     _connection     = connection;
     _credentialType = credentialType;
 }
 /// <summary>
 /// Get a credential by name.
 /// </summary>
 /// <param name="target_name">The name of the credential.</param>
 /// <param name="type">The type of credential.</param>
 /// <returns>The read credential.</returns>
 public static Credential GetCredential(string target_name, CredentialType type)
 {
     return(GetCredential(target_name, type, true).Result);
 }
Esempio n. 43
0
 internal extern static bool CredRead(
     string targetName,
     CredentialType type,
     int flags,
     [Out] out IntPtr pCredential
     );
Esempio n. 44
0
 internal extern static bool CredDelete(
     string targetName,
     CredentialType type,
     int flags
     );
 public TokenCredential CreateSingle(CredentialType credentialType, Uri authorityUri) =>
 credentialType switch
 {
Esempio n. 46
0
        /// <summary>
        /// Initialize the BWS and BWSUtil services.
        /// </summary>
        ///
        /// <returns>Returns true when the setup is successful, and false otherwise.</returns>
        private static bool setup(String hostname, String bwsPort, String username, String password,
                                  String authenticatorName, CredentialType credentialType, String domain)
        {
            const string METHOD_NAME = "setup()";

            logMessage("Entering {0}", METHOD_NAME);
            bool returnValue = false;

            REQUEST_METADATA.clientVersion   = CLIENT_VERSION;
            REQUEST_METADATA.locale          = LOCALE;
            REQUEST_METADATA.organizationUid = ORG_UID;

            logMessage("Initializing BWS web service stub");
            bwsService = new BWSService();
            logMessage("BWS web service stub initialized");
            logMessage("Initializing BWSUtil web service stub");
            bwsUtilService = new BWSUtilService();
            logMessage("BWSUtil web service stub initialized");
            // These are the URLs that point to the web services used for all calls.
            // e.g. with no port:
            // https://server01.example.net/enterprise/admin/ws
            // e.g. with port:
            // https://server01.example.net:18084/enterprise/admin/ws

            String port = "";

            if (bwsPort != null)
            {
                port = ":" + bwsPort;
            }

            bwsService.Url     = "https://" + hostname + port + "/enterprise/admin/ws";
            bwsUtilService.Url = "https://" + hostname + port + "/enterprise/admin/util/ws";

            // Set the connection timeout to 60 seconds.
            bwsService.Timeout     = 60000;
            bwsUtilService.Timeout = 60000;

            Authenticator authenticator = getAuthenticator(authenticatorName);

            if (authenticator != null)
            {
                string encodedUsername = getEncodedUserName(username, authenticator, credentialType, domain);
                if (!string.IsNullOrEmpty(encodedUsername))
                {
                    /*
                     * Set the HTTP basic authentication on the BWS service.
                     * BWSUtilService is a utility web service that does not require
                     * authentication.
                     */
                    bwsService.Credentials = new NetworkCredential(encodedUsername, password);

                    /*
                     * Send an HTTP Authorization header with requests after authentication
                     * has taken place.
                     */
                    bwsService.PreAuthenticate = true;
                    returnValue = true;
                }
                else
                {
                    logMessage("'encodedUsername' is null or empty");
                }
            }
            else
            {
                logMessage("'authenticator' is null");
            }

            logMessage("Exiting {0} with value \"{1}\"", METHOD_NAME, returnValue);
            return(returnValue);
        }
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
 /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
 /// <param name="formatProvider">not used by this TypeConverter.</param>
 /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
 /// <returns>
 /// an instance of <see cref="CredentialType" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => CredentialType.CreateFrom(sourceValue);
 internal static extern bool CredDelete(StringBuilder target, CredentialType type, int flags);
Esempio n. 49
0
        /// <summary>
        /// Get the encoded username required to authenticate user to BWS.
        /// </summary>
        /// <param name="username">A string containing the username to encode.</param>
        /// <param name="authenticator">The authenticator.</param>
        /// <returns>Returns a string containing the encoded username if successful, and a null message string
        /// otherwise.</returns>
        public static string GetEncodedUserName(string username, Authenticator authenticator)
        {
            const string methodName = "GetEncodedUserName()";
            const string bwsApiName = "bwsUtilService.getEncodedUsername()";

            logMessage("Entering {0}", methodName);
            string returnValue = null;

            GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();

            request.metadata      = Metadata;
            request.username      = username;
            request.orgUid        = Metadata.organizationUid;
            request.authenticator = authenticator;

            CredentialType credentialType = new CredentialType();

            credentialType.PASSWORD = true;
            credentialType.value    = "PASSWORD";
            request.credentialType  = credentialType;

            GetEncodedUsernameResponse response = null;

            try
            {
                logRequest(bwsApiName);
                response = bwsUtilService.getEncodedUsername(request);
                logResponse(bwsApiName, response.returnStatus.code, response.metadata);
            }
            catch (WebException e)
            {
                // Log and re-throw exception.
                logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
                throw e;
            }

            if (response.returnStatus.code.Equals("SUCCESS"))
            {
                returnValue = response.encodedUsername;
            }
            else
            {
                logMessage("Error Message: \"{0}\"", response.returnStatus.message);
            }

            // BES12 returns a Base64 encoded string while BES10 does not.  As a result, a BES10 encoded username
            // throws an exception when an attempt is made to decode from base64.  The try block will log the decoded
            // username if run against a BES12 system and the catch then logs the actual value returned by BES10.
            try
            {
                logMessage("Decoded value of encoded username \"{0}\"",
                           Encoding.Default.GetString(Convert.FromBase64String(returnValue)));
            }
            catch (Exception)
            {
                // Not actually base64 encoded. Show actual value
                logMessage("Value of encoded username \"{0}\"", returnValue);
            }
            logMessage("Exiting {0}", methodName);
            return(returnValue);
        }
Esempio n. 50
0
 internal OrganizationServiceCredentials(CredentialType credentialType)
 {
     LoadCredentialItems(credentialType);
 }
Esempio n. 51
0
        /// <summary>
        /// Saves the given Network Credential into Windows Credential store
        /// </summary>
        /// <param name="Target">Name of the application/Url where the credential is used for</param>
        /// <param name="credential">Credential to store</param>
        /// <param name="type">CredentialType</param>
        /// <param name="persistenceType">PersistenceType</param>
        /// <returns></returns>
        public static bool SaveCredentials(string Target, NetworkCredential credential, CredentialType type, PersistenceType persistenceType)
        {
            // Go ahead with what we have are stuff it into the CredMan structures.
            Credential cred = new Credential(credential);

            cred.Target          = Target;
            cred.PersistenceType = persistenceType;
            cred.Type            = type;
            bool ret       = cred.Save();
            int  lastError = Marshal.GetLastWin32Error();

            if (!ret)
            {
                throw new Win32Exception(lastError, "CredWrite throw an error");
            }
            return(ret);
        }
Esempio n. 52
0
 /// <summary>
 /// Deletes the specified target.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="type">The type.</param>
 /// <returns></returns>
 public static int Delete(string target, CredentialType type) => !CredDeleteW(target, type, 0) ? Marshal.GetHRForLastWin32Error() : 0;
Esempio n. 53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Credential" /> class.
 /// </summary>
 /// <param name="username">The username.</param>
 /// <param name="password">The password.</param>
 /// <param name="target">The string that contains the name of the credential.</param>
 public Credential(string username, string password, string target, CredentialType type)
     : this(username, password, target, type, PersistenceType.LocalComputer)
 {
 }
Esempio n. 54
0
 internal static extern bool CredDelete(string target, CredentialType type, int reservedFlag);
 [dll(advapi32, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CredDelete(string name, CredentialType type, int flags = 0);
Esempio n. 56
0
 internal static extern bool CredRead(string targetName, CredentialType type, uint flags, out IntPtr credential);
 internal static ICredentials GetCredentials(this ICredentialProvider provider, WebRequest request, CredentialType credentialType, bool retrying = false)
 {
     return(provider.GetCredentials(request.RequestUri, request.Proxy, credentialType, retrying));
 }
Esempio n. 58
0
 internal static extern bool CredDelete(string targetName, CredentialType type, uint flags);
 [dll(advapi32, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CredRead(string name, CredentialType type, int flags, out ptr cred);