public async Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, string userName, SecureString password) { await Task.Delay(0); // Not supported in .NET Core or DeviceCodeAuthentication - https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482 throw new NotSupportedException("User and password authentication is not supported in .NET Core or with DeviceCode authentication."); }
private async Task <IAccessToken> HandleAuthentication( IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters, string userName = null, SecureString password = null) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new NotSupportedException("Authenticator only works on Windows"); } IEnumerable <string> scopes = new[] { $"{environment.AzureADResource}/.default" }; BuildAuthApplication(environment, queryParameters, logger); AuthenticationResult result = null; try { var accounts = await this.AuthApplication.GetAccountsAsync(); if (accounts != null && accounts.Any()) { // This indicates there's token in cache result = await this.AuthApplication.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync(); } else { // auth application is auto cleared when there's no account BuildAuthApplication(environment, queryParameters, logger); if (!string.IsNullOrEmpty(userName) && password != null && password.Length > 0) { result = await this.AuthApplication.AcquireTokenByUsernamePassword(scopes, userName, password).ExecuteAsync(); } else { result = await this.AuthApplication.AcquireTokenInteractive(scopes).ExecuteAsync(); } } } catch (Exception ex) { throw new AuthenticationException($"Error Acquiring Token:{System.Environment.NewLine}{ex.Message}"); } if (result != null) { return(result.ToIAccessToken()); // Use the token } else { throw new AuthenticationException("Failed to acquire token"); } }
private static void AssertValidCloudEnvironment(string cloudName, IPowerBIEnvironment environment, GSEnvironments cloudEnvironments) { var cloudEnvironment = cloudEnvironments.Environments.FirstOrDefault(c => c.CloudName.Equals(cloudName, StringComparison.OrdinalIgnoreCase)); var backendService = cloudEnvironment.Services.First(s => s.Name.Equals("powerbi-backend", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual(cloudEnvironment.Services.First(s => s.Name.Equals("aad", StringComparison.OrdinalIgnoreCase)).Endpoint, environment.AzureADAuthority); AssertValidEnvironmentSharedProperties(environment); Assert.AreEqual(backendService.ResourceId, environment.AzureADResource); Assert.AreEqual(backendService.Endpoint, environment.GlobalServiceEndpoint); }
private void BuildAuthApplicationCert(IPowerBIEnvironment environment, string clientId, X509Certificate2 certificate, IPowerBILogger logger) { if (this.AuthApplicationCert == null) { this.AuthApplicationCert = ConfidentialClientApplicationBuilder .Create(environment.AzureADClientId) .WithAuthority(environment.AzureADAuthority) .WithClientId(clientId) .WithCertificate(certificate) .WithLogging((level, message, containsPii) => LoggingUtils.LogMsal(level, message, containsPii, logger)) .Build(); } }
private void BuildAuthApplicationSecret(IPowerBIEnvironment environment, string clientId, SecureString clientSecret, IPowerBILogger logger) { if (this.AuthApplicationSecret == null) { this.AuthApplicationSecret = ConfidentialClientApplicationBuilder .Create(environment.AzureADClientId) .WithAuthority(environment.AzureADAuthority) .WithClientId(clientId) .WithClientSecret(clientSecret.SecureStringToString()) .WithRedirectUri(environment.AzureADRedirectAddress) .WithLogging((level, message, containsPii) => LoggingUtils.LogMsal(level, message, containsPii, logger)) .Build(); } }
private void BuildAuthApplication(IPowerBIEnvironment environment, IDictionary <string, string> queryParameters, IPowerBILogger logger) { // auth application is auto cleared when there's no account if (this.AuthApplication == null) { var authApplicationBuilder = PublicClientApplicationBuilder .Create(environment.AzureADClientId) .WithAuthority(environment.AzureADAuthority) .WithLogging((level, message, containsPii) => LoggingUtils.LogMsal(level, message, containsPii, logger)) .WithExtraQueryParameters(queryParameters) .WithRedirectUri(environment.AzureADRedirectAddress); if (!PublicClientHelper.IsNetFramework) { authApplicationBuilder.WithRedirectUri("http://localhost"); } this.AuthApplication = authApplicationBuilder.Build(); } }
public async Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null) { IEnumerable <string> scopes = new[] { $"{environment.AzureADResource}/.default" }; if (this.AuthApplication == null) { this.AuthApplication = PublicClientApplicationBuilder .Create(environment.AzureADClientId) .WithAuthority(environment.AzureADAuthority) .WithLogging((level, message, containsPii) => LoggingUtils.LogMsal(level, message, containsPii, logger)) .WithRedirectUri(environment.AzureADRedirectAddress) .Build(); } AuthenticationResult result = null; var accounts = await AuthApplication.GetAccountsAsync(); if (accounts != null && accounts.Any()) { try { result = await AuthApplication.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync(); return(result.ToIAccessToken()); } catch (MsalUiRequiredException) { // ignore and fall through to aquire through device code } } DeviceCodeResult deviceCodeResult = null; result = await AuthApplication.AcquireTokenWithDeviceCode(scopes, r => { Console.WriteLine(r.Message); deviceCodeResult = r; return(Task.FromResult(0)); }).ExecuteAsync(); return(result.ToIAccessToken()); }
public IAccessToken Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null) { return(this.Token); }
public Task <IAccessToken> Authenticate(string userName, SecureString password, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { return(Task.FromResult(this.Token)); }
public async Task <IAccessToken> Authenticate(string clientId, string thumbprint, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { var certificate = FindCertificate(thumbprint); IEnumerable <string> scopes = new[] { $"{environment.AzureADResource}/.default" }; BuildAuthApplicationCert(environment, clientId, certificate, logger); AuthenticationResult result = null; try { var accounts = await this.AuthApplicationCert.GetAccountsAsync(); if (accounts != null && accounts.Any()) { // This indicates there's token in cache result = await this.AuthApplicationCert.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync(); } else { BuildAuthApplicationCert(environment, clientId, certificate, logger); result = await this.AuthApplicationCert.AcquireTokenForClient(scopes).ExecuteAsync(); } } catch (Exception ex) { throw new AuthenticationException($"Error Acquiring Token:{System.Environment.NewLine}{ex}"); } if (result != null) { return(result.ToIAccessToken()); // Use the token } else { throw new AuthenticationException("Failed to acquire token"); } }
private static void AssertValidEnvironmentSharedProperties(IPowerBIEnvironment environment) { Assert.AreEqual("ea0616ba-638b-4df5-95b9-636659ae5121", environment.AzureADClientId); Assert.AreEqual("urn:ietf:wg:oauth:2.0:oob", environment.AzureADRedirectAddress); }
public IAccessToken Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null) { this.InitializeUserAuthenticationFactory(logger, settings); return(UserAuthFactory.Authenticate(environment, logger, settings, queryParameters)); }
public override void ExecuteCmdlet() { IPowerBIEnvironment environment = null; // Populate custom environments from discovery url if it is present // otherwise get environment from existing settings if (!string.IsNullOrEmpty(this.DiscoveryUrl)) { if (string.IsNullOrEmpty(this.CustomEnvironment)) { throw new Exception($"{nameof(this.CustomEnvironment)} is required when using a discovery url"); } var settings = new PowerBISettings(); CustomEnvironments = new Dictionary <string, IPowerBIEnvironment>(); var customCloudEnvironments = GetServiceConfig(this.DiscoveryUrl).Result; foreach (GSEnvironment customEnvironment in customCloudEnvironments.Environments) { var backendService = customEnvironment.Services.First(s => s.Name.Equals("powerbi-backend", StringComparison.OrdinalIgnoreCase)); var redirectApp = settings.Environments[PowerBIEnvironmentType.Public]; var env = new PowerBIEnvironment() { Name = PowerBIEnvironmentType.Custom, AzureADAuthority = customEnvironment.Services.First(s => s.Name.Equals("aad", StringComparison.OrdinalIgnoreCase)).Endpoint, AzureADClientId = redirectApp.AzureADClientId, AzureADRedirectAddress = redirectApp.AzureADRedirectAddress, AzureADResource = backendService.ResourceId, GlobalServiceEndpoint = backendService.Endpoint }; this.CustomEnvironments.Add(customEnvironment.CloudName, env); } if (!this.CustomEnvironments.ContainsKey(this.CustomEnvironment)) { this.Logger.ThrowTerminatingError($"Discovery URL {this.DiscoveryUrl} did not return environment {this.CustomEnvironment}"); } environment = this.CustomEnvironments[this.CustomEnvironment]; } else { var settings = new PowerBISettings(targetEnvironmentType: this.Environment, refreshGlobalServiceConfig: true); if (settings.Environments == null) { this.Logger.ThrowTerminatingError("Failed to populate environments in settings"); } environment = settings.Environments[this.Environment]; } if (!string.IsNullOrEmpty(this.Tenant)) { var tempEnvironment = (PowerBIEnvironment)environment; tempEnvironment.AzureADAuthority = tempEnvironment.AzureADAuthority.ToLowerInvariant().Replace("/common", $"/{this.Tenant}"); this.Logger.WriteVerbose($"Updated Azure AD authority with -Tenant specified, new value: {tempEnvironment.AzureADAuthority}"); environment = tempEnvironment; } else { var tempEnvironment = (PowerBIEnvironment)environment; tempEnvironment.AzureADAuthority = tempEnvironment.AzureADAuthority.ToLowerInvariant().Replace("/common", "/organizations"); this.Logger.WriteVerbose($"Updated Azure AD authority with /organizations endpoint, new value: {tempEnvironment.AzureADAuthority}"); environment = tempEnvironment; } this.Authenticator.Challenge(); // revoke any previous login IAccessToken token = null; PowerBIProfile profile = null; switch (this.ParameterSet) { case UserParameterSet: token = this.Authenticator.Authenticate(environment, this.Logger, this.Settings, new Dictionary <string, string>() { { "msafed", "0" } } ).Result; profile = new PowerBIProfile(environment, token); break; case UserAndCredentialPasswordParameterSet: token = this.Authenticator.Authenticate(environment, this.Logger, this.Settings, this.Credential.UserName, this.Credential.Password).Result; profile = new PowerBIProfile(environment, this.Credential.UserName, this.Credential.Password, token, servicePrincipal: false); break; case ServicePrincipalCertificateParameterSet: token = this.Authenticator.Authenticate(this.ApplicationId, this.CertificateThumbprint, environment, this.Logger, this.Settings).Result; profile = new PowerBIProfile(environment, this.ApplicationId, this.CertificateThumbprint, token); break; case ServicePrincipalParameterSet: token = this.Authenticator.Authenticate(this.Credential.UserName, this.Credential.Password, environment, this.Logger, this.Settings).Result; profile = new PowerBIProfile(environment, this.Credential.UserName, this.Credential.Password, token); break; default: throw new NotImplementedException($"Parameter set {this.ParameterSet} was not implemented"); } this.Storage.SetItem("profile", profile); this.Logger.WriteObject(profile); }
public async Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, string userName, SecureString password) { return(await HandleAuthentication(environment, logger, settings, null, userName, password)); }
public async Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null) { return(await HandleAuthentication(environment, logger, settings, queryParameters)); }
private static void AssertValidEnvironmentSharedProperties(IPowerBIEnvironment environment) { Assert.AreEqual("ea0616ba-638b-4df5-95b9-636659ae5121", environment.AzureADClientId); Assert.AreEqual("https://login.microsoftonline.com/common/oauth2/nativeclient", environment.AzureADRedirectAddress); }
public PowerBIProfile(IPowerBIEnvironment environment, IAccessToken token) => (this.Environment, this.TenantId, this.UserName, this.LoginType) = (environment, token.TenantId, token.UserName, PowerBIProfileType.User);
public IAccessToken Authenticate(string userName, SecureString password, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { return(this.Token); }
public Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null) { return(Task.FromResult(this.Token)); }
public IAccessToken Authenticate(string clientId, string thumbprint, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { return(this.Token); }
public Task <IAccessToken> Authenticate(string clientId, string thumbprint, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { return(Task.FromResult(this.Token)); }
public IAccessToken Authenticate(string clientId, string thumbprint, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { this.InitializeServicePrincpalAuthenticationFactory(logger, settings); return(ServicePrincpalAuthFactory.Authenticate(clientId, thumbprint, environment, logger, settings)); }
private static void AssertValidEnvironmentSharedProperties(IPowerBIEnvironment environment) { Assert.AreEqual("23d8f6bd-1eb0-4cc2-a08c-7bf525c67bcd", environment.AzureADClientId); Assert.AreEqual("https://login.microsoftonline.com/common/oauth2/nativeclient", environment.AzureADRedirectAddress); }
public IAccessToken Authenticate(string userName, SecureString password, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings) { this.InitializeServicePrincpalAuthenticationFactory(logger, settings); return(ServicePrincpalAuthFactory.Authenticate(userName, password, environment, logger, settings)); }
public IAccessToken Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, string userName, SecureString password) { this.InitializeUserAuthenticationFactory(logger, settings); return(UserAuthFactory.Authenticate(environment, logger, settings, userName, password)); }