/// <summary> /// /// </summary> /// <param name="account"></param> /// <param name="environment"></param> /// <param name="tenant"></param> /// <param name="password"></param> /// <param name="promptBehavior"></param> /// <param name="promptAction"></param> /// <param name="tokenCache"></param> /// <param name="resourceId"></param> /// <returns></returns> public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { IAccessToken token = null; PowerShellTokenCacheProvider tokenCacheProvider; if (!AzureSession.Instance.TryGetComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out tokenCacheProvider)) { throw new NullReferenceException(Resources.AuthenticationClientFactoryNotRegistered); } Task <IAccessToken> authToken; var processAuthenticator = Builder.Authenticator; var retries = 5; while (retries-- > 0) { try { while (processAuthenticator != null && processAuthenticator.TryAuthenticate(GetAuthenticationParameters(tokenCacheProvider, account, environment, tenant, password, promptBehavior, promptAction, tokenCache, resourceId), out authToken)) { token = authToken?.ConfigureAwait(true).GetAwaiter().GetResult(); if (token != null) { // token.UserId is null when getting tenant token in ADFS environment account.Id = token.UserId ?? account.Id; if (!string.IsNullOrEmpty(token.HomeAccountId)) { account.SetProperty(AzureAccount.Property.HomeAccountId, token.HomeAccountId); } break; } processAuthenticator = processAuthenticator.Next; } } catch (Exception e) { if (!IsTransientException(e) || retries == 0) { throw e; } TracingAdapter.Information(string.Format("[AuthenticationFactory] Exception caught when calling TryAuthenticate, retrying authentication - Exception message: '{0}'", e.Message)); continue; } break; } return(token); }
public static void SetTokenCache(this IAzureContextContainer container, IAzureTokenCache cache) { if (container != null && container.DefaultContext != null) { container.DefaultContext.TokenCache = cache; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IAzureTokenCache cache = value as IAzureTokenCache; if (cache != null) { if (_serializeCache) { byte[] cacheData = null; if (AzureSession.Instance.TryGetComponent( PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out PowerShellTokenCacheProvider tokenCacheProvider)) { cacheData = tokenCacheProvider.ReadTokenData(); } value = new CacheBuffer { CacheData = cacheData }; } else { value = new CacheBuffer(); } } serializer.Serialize(writer, value); }
public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } if (TokenProvider == null) { return(new MockAccessToken() { AccessToken = account.Id, LoginType = LoginType.OrgId, UserId = account.Id }); } else { return(TokenProvider(account, environment, tenant)); } }
/// <summary> /// Remove a user from token cache. /// </summary> /// <param name="account"></param> /// <param name="tokenCache">This parameter is no longer used. However to keep the API unchanged it's not removed.</param> public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache) { if (account != null && !string.IsNullOrEmpty(account.Id) && !string.IsNullOrWhiteSpace(account.Type)) { switch (account.Type) { case AzureAccount.AccountType.AccessToken: account.SetProperty(AzureAccount.Property.AccessToken, null); account.SetProperty(AzureAccount.Property.GraphAccessToken, null); account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, null); break; case AzureAccount.AccountType.ManagedService: account.SetProperty(AzureAccount.Property.MSILoginUri, null); break; case AzureAccount.AccountType.ServicePrincipal: try { KeyStore.DeleteKey(account.Id, account.GetTenants().FirstOrDefault()); } catch { // make best effort to remove credentials } RemoveFromTokenCache(account); break; case AzureAccount.AccountType.User: RemoveFromTokenCache(account); break; } } }
private AuthenticationParameters GetAuthenticationParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { switch (account.Type) { case AzureAccount.AccountType.User: if (password == null) { var homeAccountId = account.GetProperty(AzureAccount.Property.HomeAccountId) ?? ""; if (!string.IsNullOrEmpty(account.Id)) { return(new SilentParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId)); } if (account.IsPropertySet("UseDeviceAuth")) { return(new DeviceCodeParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId)); } else if (account.IsPropertySet(AzureAccount.Property.UsePasswordAuth)) { return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, homeAccountId)); } return(new InteractiveParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, homeAccountId, promptAction)); } return(new UsernamePasswordParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, password, null)); case AzureAccount.AccountType.Certificate: case AzureAccount.AccountType.ServicePrincipal: bool?sendCertificateChain = null; var sendCertificateChainStr = account.GetProperty(AzureAccount.Property.SendCertificateChain); if (!string.IsNullOrWhiteSpace(sendCertificateChainStr)) { sendCertificateChain = Boolean.Parse(sendCertificateChainStr); } password = password ?? ConvertToSecureString(account.GetProperty(AzureAccount.Property.ServicePrincipalSecret)); var certificatePassword = ConvertToSecureString(account.GetProperty(AzureAccount.Property.CertificatePassword)); return(new ServicePrincipalParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account.Id, account.GetProperty(AzureAccount.Property.CertificateThumbprint), account.GetProperty(AzureAccount.Property.CertificatePath), certificatePassword, password, sendCertificateChain)); case AzureAccount.AccountType.ManagedService: return(new ManagedServiceIdentityParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account)); case AzureAccount.AccountType.AccessToken: return(new AccessTokenParameters(tokenCacheProvider, environment, tokenCache, tenant, resourceId, account)); default: return(null); } }
/// <summary> /// Populate a token cache from a PSObject /// </summary> /// <param name="cache">The cache to populate</param> /// <param name="other">The object to populate from</param> public static void Populate(this IAzureTokenCache cache, PSObject other) { byte[] data; if (other.TryGetProperty(nameof(cache.CacheData), out data)) { cache.CacheData = data; } }
public ManagedServiceIdentityParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, IAzureAccount account) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { Account = account; }
public RMProfileClient(AzureRmProfile profile) { _profile = profile; var context = _profile.DefaultContext; if (_profile != null && context != null && context.TokenCache != null) { _cache = context.TokenCache; } }
public static IAzureTokenCache GetTokenCache(this IAzureContextContainer container) { IAzureTokenCache result = null; if (HasTokenCache(container)) { result = container.DefaultContext.TokenCache; } return(result); }
public ClientAssertionParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, string clientId, SecureString clientAssertion) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { this.ClientId = clientId; this.ClientAssertion = clientAssertion; }
public InteractiveParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, string userId, string homeAccountId, Action <string> promptAction) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId, userId, homeAccountId) { PromptAction = promptAction; }
public RMProfileClient(IProfileOperations profile) { _profile = profile; var context = _profile.DefaultContext; _cache = AzureSession.Instance.TokenCache; if (_profile != null && context != null && context.TokenCache != null) { _cache = context.TokenCache; } }
public SilentParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, string userId, string homeAccountId) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { UserId = userId; HomeAccountId = homeAccountId; }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IAzureTokenCache cache = value as IAzureTokenCache; if (cache != null) { value = new CacheBuffer { CacheData = cache.CacheData }; } serializer.Serialize(writer, value); }
public RMProfileClient(IProfileOperations profile) { _profile = profile; var context = _profile.DefaultContext; _cache = AzureSession.Instance.TokenCache; if (_profile != null && context != null && context.TokenCache != null) { _cache = context.TokenCache; } SubscriptionAndTenantClient = new SubscriptionClientProxy(t => WriteWarningMessage(t)); }
public AuthenticationParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId) { TokenCacheProvider = tokenCacheProvider; Environment = environment; TokenCache = tokenCache; TenantId = tenantId; ResourceId = resourceId; }
public ServicePrincipalParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, string applicationId, string thumbprint, SecureString secret) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { ApplicationId = applicationId; Thumbprint = thumbprint; Secret = secret; }
public UsernamePasswordParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, string userId, SecureString password, string homeAccountId) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { UserId = userId; Password = password; HomeAccountId = homeAccountId; }
public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { IAccessToken token; var cache = tokenCache as TokenCache; if (cache == null) { cache = TokenCache.DefaultShared; } var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache); TracingAdapter.Information( Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) { var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint); #if !NETSTANDARD token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type); #else throw new NotSupportedException("Certificate based authentication is not supported in netcore version."); #endif } else { token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type); } account.Id = token.UserId; return(token); }
/// <summary> /// Check if two token caches are equal /// </summary> /// <param name="cache">The base cache</param> /// <param name="other">The cache to compare with</param> /// <returns>True if the two caches contain the same data, otherwise false</returns> public static bool IsEqual(this IAzureTokenCache cache, IAzureTokenCache other) { bool result = (cache == null && other == null) || (cache != null && cache.CacheData == null && other != null && other.CacheData == null); if (cache != null && other != null && cache.CacheData != null && other.CacheData != null && cache.CacheData.Length == other.CacheData.Length) { result = true; for (int i = 0; i < cache.CacheData.Length; ++i) { if (cache.CacheData[i] != other.CacheData[i]) { result = false; } } } return(result); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IAzureTokenCache cache = value as IAzureTokenCache; if (cache != null) { if (_serializeCache) { byte[] cacheData = null; if (AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache)) { if (tokenCache.IsPersistentCache) { if (AzureSession.Instance.TryGetComponent( PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out PowerShellTokenCacheProvider tokenCacheProvider)) { cacheData = tokenCacheProvider.ReadTokenData(); } } else { using (var stream = new MemoryStream()) { tokenCache.Serialize(stream); cacheData = stream.ToArray(); } } } value = new CacheBuffer { CacheData = cacheData }; } else { value = new CacheBuffer(); } } serializer.Serialize(writer, value); }
public ServicePrincipalParameters( PowerShellTokenCacheProvider tokenCacheProvider, IAzureEnvironment environment, IAzureTokenCache tokenCache, string tenantId, string resourceId, string applicationId, string thumbprint, string certificatePath, SecureString certificateSecret, SecureString secret, bool?sendCertificateChain) : base(tokenCacheProvider, environment, tokenCache, tenantId, resourceId) { ApplicationId = applicationId; Thumbprint = thumbprint; Secret = secret; SendCertificateChain = sendCertificateChain; CertificatePath = certificatePath; CertificateSecret = certificateSecret; }
protected override void BeginProcessing() { _profile = new AzureRmAutosaveProfile( (DefaultProfile as AzureRmProfile), ProtectedFileProvider.CreateFileProvider( Path.Combine(AzureSession.Instance.ARMProfileDirectory, AzureSession.Instance.ARMProfileFile), FileProtection.ExclusiveWrite)); var context = _profile.DefaultContext; _cache = AzureSession.Instance.TokenCache; if (_profile != null && context != null && context.TokenCache != null) { _cache = context.TokenCache; } _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud]; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { _credential = new PSCredential(UserName, ConvertToSecureString(Password)); } base.BeginProcessing(); }
public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { if (account.Id == null) { account.Id = "test"; } var token = new MockAccessToken { UserId = account.Id, LoginType = LoginType.OrgId, AccessToken = "123" }; return(token); }
public IAccessToken Authenticate( IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Action <string> promptAction, IAzureTokenCache tokenCache, string resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId) { IAccessToken token; var cache = tokenCache as TokenCache; if (cache == null) { cache = TokenCache.DefaultShared; } var configuration = GetAdalConfiguration(environment, tenant, resourceId, cache); TracingAdapter.Information( Resources.AdalAuthConfigurationTrace, configuration.AdDomain, configuration.AdEndpoint, configuration.ClientId, configuration.ClientRedirectUri, configuration.ResourceClientUri, configuration.ValidateAuthority); if (account != null && account.Type == AzureAccount.AccountType.ManagedService) { token = GetManagedServiceToken(account, environment, tenant, resourceId); } else if (account != null && environment != null && account.Type == AzureAccount.AccountType.AccessToken) { var rawToken = new RawAccessToken { TenantId = tenant, UserId = account.Id, LoginType = AzureAccount.AccountType.AccessToken }; if ((string.Equals(resourceId, environment.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) || string.Equals(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) && account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken)) { rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken); } else if ((string.Equals(resourceId, environment.GraphEndpointResourceId, StringComparison.OrdinalIgnoreCase) || string.Equals(AzureEnvironment.Endpoint.GraphEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) && account.IsPropertySet(AzureAccount.Property.GraphAccessToken)) { rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken); } else if ((string.Equals(resourceId, environment.ActiveDirectoryServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase) || string.Equals(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase)) && account.IsPropertySet(AzureAccount.Property.AccessToken)) { rawToken.AccessToken = account.GetAccessToken(); } else { throw new InvalidOperationException(string.Format(Resources.AccessTokenResourceNotFound, resourceId)); } token = rawToken; } else if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint)) { var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint); #if !NETSTANDARD token = TokenProvider.GetAccessTokenWithCertificate(configuration, account.Id, thumbprint, account.Type); #else throw new NotSupportedException("Certificate based authentication is not supported in netcore version."); #endif } else { token = TokenProvider.GetAccessToken(configuration, promptBehavior, promptAction, account.Id, password, account.Type); } account.Id = token.UserId; return(token); }
public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache) { throw new NotImplementedException(); }
public async override Task <IAccessToken> Authenticate(IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Task <Action <string> > promptAction, IAzureTokenCache tokenCache, string resourceId) { var auth = new AuthenticationContext(AuthenticationHelpers.GetAuthority(environment, tenant), environment?.OnPremise ?? true, tokenCache as TokenCache ?? TokenCache.DefaultShared); var response = await auth.AcquireTokenAsync( environment.GetEndpoint(resourceId), AuthenticationHelpers.PowerShellClientId, new Uri(AuthenticationHelpers.PowerShellRedirectUri), new PlatformParameters(AuthenticationHelpers.GetPromptBehavior(promptBehavior), new ConsoleParentWindow()), UserIdentifier.AnyUser, AuthenticationHelpers.EnableEbdMagicCookie); account.Id = response?.UserInfo?.DisplayableId; return(AuthenticationResultToken.GetAccessToken(response)); }
public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache) { }
public override bool CanAuthenticate(IAzureAccount account, IAzureEnvironment environment, string tenant, SecureString password, string promptBehavior, Task <Action <string> > promptAction, IAzureTokenCache tokenCache, string resourceId) { return(account?.Type == AzureAccount.AccountType.User && environment != null && !string.IsNullOrWhiteSpace(tenant) && password == null && promptBehavior != ShowDialog.Never && tokenCache != null && account != null && !account.IsPropertySet("UseDeviceAuth")); }