public bool CreatePublicClient(bool prompt, bool deviceLogin = false)
        {
            Log.Info($"enter: {prompt} {deviceLogin}");
            _publicClientApp = PublicClientApplicationBuilder
                               .Create(_wellKnownClientId)
                               .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId)
                               .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                               .WithDefaultRedirectUri()
                               .Build();

            if (_instance.IsWindows)
            {
                TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache);
            }

            if (prompt)
            {
                if (deviceLogin)
                {
                    AuthenticationResult = _publicClientApp
                                           .AcquireTokenWithDeviceCode(_defaultScope, MsalDeviceCodeCallback)
                                           .ExecuteAsync().Result;
                }
                else
                {
                    AuthenticationResult = _publicClientApp
                                           .AcquireTokenInteractive(_defaultScope)
                                           .ExecuteAsync().Result;
                }
            }
            else
            {
                AuthenticationResult = _publicClientApp
                                       .AcquireTokenSilent(_defaultScope, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault())
                                       .ExecuteAsync().Result;
            }

            if (Scopes.Count > 0)
            {
                Log.Info($"adding scopes {Scopes.Count}");
                AuthenticationResult = _publicClientApp
                                       .AcquireTokenSilent(Scopes, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault())
                                       .ExecuteAsync().Result;
            }

            return(true);
        }
Ejemplo n.º 2
0
        public bool CreatePublicClient(bool prompt, bool deviceLogin = false)
        {
            Log.Info($"enter: {prompt} {deviceLogin}");
            AuthenticationResult result = null;

            _publicClientApp = PublicClientApplicationBuilder
                               .Create(_wellKnownClientId)
                               .WithAuthority(AzureCloudInstance.AzurePublic, _config.AzureTenantId)
                               .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                               .WithDefaultRedirectUri()
                               .Build();

            TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache);

            if (prompt)
            {
                if (deviceLogin)
                {
                    result = _publicClientApp.AcquireTokenWithDeviceCode(_defaultScope, MsalDeviceCodeCallback).ExecuteAsync().Result;
                }
                else
                {
                    result = _publicClientApp.AcquireTokenInteractive(_defaultScope).ExecuteAsync().Result;
                }
            }
            else
            {
                IAccount hint = _publicClientApp.GetAccountsAsync().Result.FirstOrDefault();

                if (hint == null && !TokenCacheHelper.HasTokens)
                {
                    throw new MsalUiRequiredException("unable to acquire token silently.", "no hint and no cached tokens.");
                }

                result = _publicClientApp.AcquireTokenSilent(_defaultScope, hint).ExecuteAsync().Result;
            }

            if (Scopes.Count > 0)
            {
                Log.Info($"adding scopes {Scopes.Count}");
                result = _publicClientApp.AcquireTokenSilent(Scopes, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault()).ExecuteAsync().Result;
            }

            AuthenticationResultToken = new AccessToken(result.AccessToken, result.ExpiresOn);
            return(true);
        }
Ejemplo n.º 3
0
        public bool CreateConfidentialClient(string resource)
        {
            Log.Info($"enter: {resource}");
            // no prompt with clientid and secret
            _confidentialClientApp = ConfidentialClientApplicationBuilder
                                     .CreateWithApplicationOptions(new ConfidentialClientApplicationOptions
            {
                ClientId     = Config.AzureClientId,
                RedirectUri  = resource,
                ClientSecret = Config.AzureClientSecret,
                TenantId     = Config.AzureTenantId,
                ClientName   = Config.AzureClientId
            })
                                     .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId)
                                     .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                                     .Build();

            if (Scopes.Count < 1)
            {
                Scopes = _defaultScope;
            }

            if (_instance.IsWindows)
            {
                TokenCacheHelper.EnableSerialization(_confidentialClientApp.AppTokenCache);
            }

            foreach (string scope in Scopes)
            {
                AuthenticationResult = _confidentialClientApp
                                       .AcquireTokenForClient(new List <string>()
                {
                    scope
                })
                                       .ExecuteAsync().Result;
                Log.Debug($"scope authentication result:", AuthenticationResult);
            }

            return(true);
        }
Ejemplo n.º 4
0
        private void AddClientScopes(bool sendX5C = false)
        {
            if (Scopes.Count < 1)
            {
                Scopes = _defaultScope;
            }

            TokenCacheHelper.EnableSerialization(_confidentialClientApp.AppTokenCache);

            foreach (string scope in Scopes)
            {
                AuthenticationResult result = _confidentialClientApp
                                              .AcquireTokenForClient(new List <string>()
                {
                    scope
                })
                                              .WithSendX5C(sendX5C)
                                              .ExecuteAsync().Result;
                Log.Debug($"scope authentication result:", AuthenticationResultToken);
                AuthenticationResultToken = new AccessToken(result.AccessToken, result.ExpiresOn);
            }
        }
        private void AddClientScopes()
        {
            if (Scopes.Count < 1)
            {
                Scopes = _defaultScope;
            }

            if (_instance.IsWindows)
            {
                TokenCacheHelper.EnableSerialization(_confidentialClientApp.AppTokenCache);
            }

            foreach (string scope in Scopes)
            {
                AuthenticationResult = _confidentialClientApp
                                       .AcquireTokenForClient(new List <string>()
                {
                    scope
                })
                                       .ExecuteAsync().Result;
                Log.Debug($"scope authentication result:", AuthenticationResult);
            }
        }
Ejemplo n.º 6
0
        public bool Authenticate(bool throwOnError = false, string resource = ManagementAzureCom, bool prompt = false)
        {
            Log.Debug("azure ad:enter");
            _resource = resource;

            if (_tokenExpirationHalfLife > DateTime.Now)
            {
                Log.Debug("token still valid");
                return(false);
            }
            else if (!IsAuthenticated)
            {
                Log.Info("authenticating to azure", ConsoleColor.Green);
            }
            else
            {
                Log.Warning($"refreshing aad token. token expiration half life: {_tokenExpirationHalfLife}");
            }

            try
            {
                if (string.IsNullOrEmpty(Config.AzureTenantId))
                {
                    Config.AzureTenantId = _commonTenantId;
                }

                if (Config.IsClientIdConfigured())
                {
                    // no prompt with clientid and secret
                    _confidentialClientApp = ConfidentialClientApplicationBuilder
                                             .CreateWithApplicationOptions(new ConfidentialClientApplicationOptions
                    {
                        ClientId     = Config.AzureClientId,
                        RedirectUri  = resource,
                        ClientSecret = Config.AzureClientSecret,
                        TenantId     = Config.AzureTenantId,
                        ClientName   = Config.AzureClientId
                    })
                                             .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId)
                                             .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                                             .Build();

                    if (Scopes.Count < 1)
                    {
                        Scopes = _defaultScope;
                    }

                    foreach (string scope in Scopes)
                    {
                        TokenCacheHelper.EnableSerialization(_confidentialClientApp.AppTokenCache);
                        AuthenticationResult = _confidentialClientApp
                                               .AcquireTokenForClient(new List <string>()
                        {
                            scope
                        })
                                               .ExecuteAsync().Result;
                        Log.Debug($"scope authentication result:", AuthenticationResult);
                    }
                }
                else
                {
                    _publicClientApp = PublicClientApplicationBuilder
                                       .Create(_wellKnownClientId)
                                       .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId)
                                       .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                                       .WithDefaultRedirectUri()
                                       .Build();

                    TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache);
                    AuthenticationResult = _publicClientApp
                                           .AcquireTokenSilent(_defaultScope, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault())
                                           .ExecuteAsync().Result;

                    if (Scopes.Count > 0)
                    {
                        Log.Info($"adding scopes {Scopes.Count}");
                        AuthenticationResult = _publicClientApp
                                               .AcquireTokenSilent(Scopes, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault())
                                               .ExecuteAsync().Result;
                    }
                }

                BearerToken = AuthenticationResult.AccessToken;
                long tickDiff = ((AuthenticationResult.ExpiresOn.ToLocalTime().Ticks - DateTime.Now.Ticks) / 2) + DateTime.Now.Ticks;
                _tokenExpirationHalfLife = new DateTimeOffset(new DateTime(tickDiff));

                Log.Info($"authentication result:", ConsoleColor.Green, null, AuthenticationResult);
                Log.Highlight($"aad token expiration: {AuthenticationResult.ExpiresOn.ToLocalTime()}");
                Log.Highlight($"aad token half life expiration: {_tokenExpirationHalfLife}");

                _timer          = new Timer(Reauthenticate, null, Convert.ToInt32((_tokenExpirationHalfLife - DateTime.Now).TotalMilliseconds), Timeout.Infinite);
                IsAuthenticated = true;

                return(true);
            }
            catch (MsalUiRequiredException)
            {
                if (!Config.IsClientIdConfigured())
                {
                    AuthenticationResult = _publicClientApp
                                           .AcquireTokenInteractive(_defaultScope)
                                           .ExecuteAsync().Result;
                    return(Authenticate(throwOnError, resource, true));
                }

                if (throwOnError)
                {
                    throw;
                }

                IsAuthenticated = false;
                return(false);
            }
            catch (AggregateException ae)
            {
                Log.Exception($"aggregate exception:{ae}");

                if (ae.GetBaseException() is MsalException)
                {
                    MsalException me = ae.GetBaseException() as MsalException;
                    Log.Exception($"msal exception:{me}");

                    if (me.ErrorCode.Contains("interaction_required") && !prompt)
                    {
                        return(Authenticate(throwOnError, resource, true));
                    }
                }

                return(false);
            }
            catch (Exception e)
            {
                Log.Exception($"{e}");

                if (throwOnError)
                {
                    throw;
                }

                IsAuthenticated = false;
                return(false);
            }
        }