示例#1
0
        public static void LogMsal(
            LogLevel level,
            string message,
            bool containsPii,
            IPowerBILogger logger)
        {
            Action <string> logWithLevel;

            switch (level)
            {
            case LogLevel.Error:
            case LogLevel.Warning:
                logWithLevel = logger.WriteWarning;
                break;

            case LogLevel.Info:
                logWithLevel = logger.WriteDebug;
                break;

            case LogLevel.Verbose:
            default:
                logWithLevel = logger.WriteVerbose;
                break;
            }

            logWithLevel(message);
        }
示例#2
0
        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 void InitializeServicePrincpalAuthenticationFactory(IPowerBILogger logger, IPowerBISettings settings)
        {
            if (ServicePrincipalAuthFactory == null)
            {
                if (ServicePrincipalAuthFactory == null)
                {
                    ServicePrincipalAuthFactory = new ServicePrincipalAuthenticationFactory();
                }
            }

            BaseAuthFactory = ServicePrincipalAuthFactory;
        }
        private void InitializeUserAuthenticationFactory(IPowerBILogger logger, IPowerBISettings settings)
        {
            if (UserAuthFactory == null)
            {
                bool forceDeviceAuth = settings.Settings.ForceDeviceCodeAuthentication;
                if (!forceDeviceAuth && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    UserAuthFactory = new WindowsAuthenticationFactory();
                }
                else
                {
                    UserAuthFactory = new DeviceCodeAuthenticationFactory();
                }
            }

            BaseAuthFactory = UserAuthFactory;
        }
        public IAccessToken Authenticate(IPowerBIProfile profile, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null)
        {
            switch (profile.LoginType)
            {
            case PowerBIProfileType.User:
                return(this.Authenticate(profile.Environment, logger, settings, queryParameters));

            case PowerBIProfileType.ServicePrincipal:
                return(this.Authenticate(profile.UserName, profile.Password, profile.Environment, logger, settings));

            case PowerBIProfileType.Certificate:
                return(this.Authenticate(profile.UserName, profile.Thumbprint, profile.Environment, logger, settings));

            default:
                throw new NotSupportedException();
            }
        }
示例#6
0
        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.");
        }
示例#7
0
        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 Task <IAccessToken> Authenticate(string clientId, string thumbprint, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings)
 {
     return(Task.FromResult(this.Token));
 }
 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, IDictionary <string, string> queryParameters = null)
 {
     this.InitializeUserAuthenticationFactory(logger, settings);
     return(UserAuthFactory.Authenticate(environment, logger, settings, queryParameters));
 }
        private static IPowerBIClient CreateClient(IAuthenticationFactory authenticator, IPowerBIProfile profile, IPowerBILogger logger, IPowerBISettings settings, HttpClientHandler httpClientHandler)
        {
            var token = authenticator.Authenticate(profile, logger, settings);

            if (Uri.TryCreate(profile.Environment.GlobalServiceEndpoint, UriKind.Absolute, out Uri baseUri))
            {
                return(new PowerBIClient(baseUri, new TokenCredentials(token.AccessToken), httpClientHandler));
            }
            else
            {
                return(new PowerBIClient(new TokenCredentials(token.AccessToken), httpClientHandler));
            }
        }
示例#12
0
 public IAccessToken Authenticate(string clientId, string thumbprint, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings)
 {
     return(this.Token);
 }
示例#13
0
 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();
     }
 }
示例#14
0
 public PowerBIHttpClientHandler(IPowerBILogger logger)
 {
     this.Logger = logger;
 }
 public Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null)
 {
     return(Task.FromResult(this.Token));
 }
示例#16
0
 public async Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, string userName, SecureString password)
 {
     return(await HandleAuthentication(environment, logger, settings, null, userName, password));
 }
示例#17
0
 public async Task <IAccessToken> Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null)
 {
     return(await HandleAuthentication(environment, logger, settings, queryParameters));
 }
示例#18
0
        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();
            }
        }
示例#19
0
 public IAccessToken Authenticate(IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings, IDictionary <string, string> queryParameters = null)
 {
     return(this.Token);
 }
示例#20
0
 public IAccessToken Authenticate(string userName, SecureString password, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings)
 {
     return(this.Token);
 }
示例#21
0
 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();
     }
 }
 public PowerBIApiClient(IAuthenticationFactory authenticator, IPowerBIProfile profile, IPowerBILogger logger, IPowerBISettings settings, HttpClientHandler httpClientHandler)
 {
     this.Client = CreateClient(authenticator, profile, logger, settings, httpClientHandler);
     InitializeClients();
 }
示例#23
0
        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");
            }
        }
 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));
 }
 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));
 }
        private static IGatewayClient CreateGatewaysClient(IAuthenticationFactory authenticator, IPowerBIProfile profile, IPowerBILogger logger, IPowerBISettings settings, HttpClientHandler httpClientHandler)
        {
            var token = authenticator.Authenticate(profile, logger, settings);

            if (Uri.TryCreate(profile.Environment.GlobalServiceEndpoint, UriKind.Absolute, out Uri baseUri))
            {
                return(new GatewayClient(baseUri, token, httpClientHandler));
            }

            throw new ArgumentNullException(nameof(IPowerBIEnvironment.GlobalServiceEndpoint));
        }
 public PowerBIApiClient(IAuthenticationFactory authenticator, IPowerBIProfile profile, IPowerBILogger logger, IPowerBISettings settings)
 {
     this.Client   = CreateClient(authenticator, profile, logger, settings);
     this.Gateways = CreateGatewaysClient(authenticator, profile, logger, settings);
     InitializeClients();
 }
示例#28
0
 public IPowerBIApiClient CreateClient(IAuthenticationFactory authenticator, IPowerBIProfile profile, IPowerBILogger logger, IPowerBISettings settings)
 {
     return(new PowerBIApiClient(authenticator, profile, logger, settings, new PowerBIHttpClientHandler(logger)));
 }
 public Task <IAccessToken> Authenticate(string userName, SecureString password, IPowerBIEnvironment environment, IPowerBILogger logger, IPowerBISettings settings)
 {
     return(Task.FromResult(this.Token));
 }