Exemplo n.º 1
0
        public async Task AuthenticateResourceAsync_HandleAdalException()
        {
            this.adalServiceInfo.ClientSecret = "clientSecret";

            var resource = "https://resource.sharepoint.com/";
            var expectedAuthenticationResult = new MockAuthenticationResult();

            var adalException = new AdalException("code");

            this.authenticationContextWrapper
            .Setup(wrapper => wrapper.AcquireTokenByAuthorizationCodeAsync(
                       It.IsAny <string>(),
                       It.IsAny <Uri>(),
                       It.IsAny <ClientCredential>(),
                       It.IsAny <string>()))
            .Throws(adalException);

            try
            {
                var authenticationResult = await this.authenticationProvider.AuthenticateResourceAsyncWrapper(resource);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("An error occurred during Azure Active Directory authentication.", exception.Error.Message, "Unexpected error thrown.");
                Assert.AreEqual(adalException, exception.InnerException, "Unexpected inner exception.");
                throw;
            }
        }
Exemplo n.º 2
0
        public SecurityToken RequestToken(string issuer, string appliesTo, RecordsManagerCredentials credentials)
        {
            var authContext = new AuthenticationContext(Constants.WAAD_AUTHORITY);

            AuthenticationResult result = null;

            // first, try to get a token silently
            try
            {
                result = authContext.AcquireTokenSilentAsync(appId, Constants.WAAD_CLIENTID).Result;
            }
            catch (AggregateException exc)
            {
                AdalException ex = exc.InnerException as AdalException;

                // There is no token in the cache; prompt the user to sign-in.
                if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently")
                {
                    throw;
                }
            }

            if (result == null)
            {
                result = this.RunSync(async() =>
                {
                    return(await authContext.AcquireTokenAsync(appId, Constants.WAAD_CLIENTID, new UserPasswordCredential(credentials.Username, credentials.Password)));
                });
            }

            return(new SecurityToken(result.AccessToken, result.AccessTokenType, result.ExpiresOn.DateTime));
        }
Exemplo n.º 3
0
        private async Task <string> GetAzureKeyVaultAccessTokenAsync(
            AuthenticationContext authenticationContext,
            UserCredential userCredential,
            string resourceId,
            string clientId) //scope
        {
            AuthenticationResult result = null;

            // first, try to get a token silently
            try
            {
                result = authenticationContext.AcquireTokenSilentAsync(resourceId, clientId).Result;
            }
            catch (AggregateException exc)
            {
                AdalException ex = exc.InnerException as AdalException;

                // There is no token in the cache; prompt the user to sign-in.
                if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently") //this is an expected error
                {
                    // An unexpected error occurred.
                    throw ex;
                }
            }

            //try to acquire token by explicitly providing credentials
            if (result == null)
            {
                result = await authenticationContext.AcquireTokenAsync(resourceId, clientId, userCredential);
            }

            return(result.AccessToken);
        }
 /// <summary>
 /// Creates custom AAD Client exception
 /// </summary>
 /// <param name="adalException">ADAL Exception object</param>
 private static void HandleAzureActiveDirectoryClientException(AdalException adalException)
 {
     if (!string.IsNullOrEmpty(adalException.ErrorCode))
     {
         //trace.TraceWarning($"AzureActiveDirectoryClientException;ErrorCode={adalException.ErrorCode}, AdalException={adalException}");
     }
     else
     {
         //trace.TraceWarning($"AzureActiveDirectoryClientException;ErrorMessage={adalException.Message}, AdalException={adalException}");
     }
 }
Exemplo n.º 5
0
    private void HandleAdalException(AdalException e, IAADLogger Logger)
    {
        // Exception: AdalException
        // Represents a library exception generated by ADAL .NET.
        // e.ErrorCode contains the error code

        // Action: Case 1, Non-Retryable
        // Do not perform an immediate retry. Only retry after user action.
        // Example Errors: network_not_available, default case
        Logger.Log($"AdalException Message: {e.Message}");
        Logger.Log($"AdalException Error Code: {e.ErrorCode.ToString()}");
    }
        static public void Log(AdalException authException, ref string strErrors)
        {
            string strMessage = authException.Message;
            string strDetail  = null;

            if (authException.InnerException != null)
            {
                // You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                // InnerException.Message contains the HTTP error status codes mentioned in the link above
                strDetail  = authException.InnerException.Message;
                strErrors += strDetail;
            }
            GraphHelperEventSource.Log.AuthFailure(strMessage, strDetail);
        }
        private void VerifyNotOnMainThread()
        {
            Looper looper = Looper.MyLooper();

            if (looper != null && looper == mContext.MainLooper)
            {
                Exception exception = new AdalException(
                    "calling this from your main thread can lead to deadlock");

                CallState.Logger.Error(null, exception.ToString());
                CallState.Logger.ErrorPii(null, exception);

                if (mContext.ApplicationInfo.TargetSdkVersion >= BuildVersionCodes.Froyo)
                {
                    throw exception;
                }
            }
        }
        public Intent GetIntentForBrokerActivity(AuthenticationRequest request, Activity callerActivity)
        {
            Intent intent = null;
            IAccountManagerFuture result = null;

            try
            {
                // Callback is not passed since it is making a blocking call to get
                // intent. Activity needs to be launched from calling app
                // to get the calling app's metadata if needed at BrokerActivity.
                Bundle addAccountOptions = GetBrokerOptions(request);
                result = mAcctManager.AddAccount(BrokerConstants.BrokerAccountType,
                                                 BrokerConstants.AuthtokenType, null, addAccountOptions, null,
                                                 null, new Handler(callerActivity.MainLooper));

                // Making blocking request here
                Bundle bundleResult = (Bundle)result.Result;
                // Authenticator should throw OperationCanceledException if
                // token is not available
                intent = (Intent)bundleResult.GetParcelable(AccountManager.KeyIntent);

                // Add flag to this intent to signal that request is for broker
                // logic
                if (intent != null)
                {
                    intent.PutExtra(BrokerConstants.BrokerRequest, BrokerConstants.BrokerRequest);
                }
            }
            catch (OperationCanceledException e)
            {
                CallState.Logger.Error(null, e);
                CallState.Logger.ErrorPii(null, e);
            }
            catch (Exception e)
            {
                // Authenticator gets problem from webrequest or file read/write
                var ex = new AdalException("Authenticator cancels the request", e);
                CallState.Logger.Error(null, ex);
                CallState.Logger.ErrorPii(null, ex);
            }

            return(intent);
        }
        public async Task UserRealmDiscoveryTest()
        {
            AuthenticationContext context = new AuthenticationContext(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/"
                                                                      + TestConstants.DefaultDisplayableId, new TokenCache());
            await context.Authenticator.UpdateFromTemplateAsync(null);

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/"
                                                                                + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Federated\",\"domain_name\":\"microsoft.com\"," +
                                                "\"federation_protocol\":\"WSTrust\",\"federation_metadata_url\":" +
                                                "\"https://msft.sts.microsoft.com/adfs/services/trust/mex\"," +
                                                "\"federation_active_auth_url\":\"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed\"" +
                                                ",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });

            UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, TestConstants.DefaultDisplayableId,
                                                                                                                   CallState.Default);

            VerifyUserRealmResponse(userRealmResponse, "Federated");

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/"
                                                                                + TestConstants.DefaultDisplayableId)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("{\"ver\":\"1.0\",\"account_type\":\"Unknown\",\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                },
                QueryParams = new Dictionary <string, string>()
                {
                    { "api-version", "1.0" }
                }
            });
            userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, TestConstants.DefaultDisplayableId, CallState.Default);

            VerifyUserRealmResponse(userRealmResponse, "Unknown");

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetUserRealmEndpoint(TestConstants.DefaultAuthorityCommonTenant) + "/"
                                                                                + null)
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateFailureResponseMessage("unknown_user")
            });

            AdalException ex = AssertException.TaskThrows <AdalException>(() =>
                                                                          UserRealmDiscoveryResponse.CreateByDiscoveryAsync(context.Authenticator.UserRealmUri, null, CallState.Default));

            Assert.AreEqual(AdalError.UnknownUser, ex.Message);

            // All mocks are consumed
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockHandlersCount());
        }
Exemplo n.º 10
0
        public bool Authenticate(bool throwOnError = false, string resource = ManagementAzureCom, PromptBehavior prompt = PromptBehavior.Never)
        {
            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
            {
                AuthenticationContext authContext = new AuthenticationContext(
                    _baseAuthUrl + (string.IsNullOrEmpty(Config.AzureTenantId) ? "common" : Config.AzureTenantId), _tokenCache);

                if (Config.IsClientIdConfigured())
                {
                    // no prompt with clientid and secret
                    AuthenticationResult = authContext.AcquireTokenAsync(resource,
                                                                         new ClientCredential(Config.AzureClientId, Config.AzureClientSecret)).Result;
                }
                else
                {
                    // normal azure auth with prompt if needed
                    AuthenticationResult = authContext.AcquireTokenAsync(resource,
                                                                         _wellKnownClientId,
                                                                         _replyUrl,
                                                                         new PlatformParameters(prompt)).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 (AggregateException ae)
            {
                Log.Exception($"aggregate exception:{ae}");

                if (ae.GetBaseException() is AdalException)
                {
                    AdalException ad = ae.GetBaseException() as AdalException;
                    Log.Exception($"adal exception:{ad}");

                    if (ad.ErrorCode.Contains("interaction_required") && prompt == PromptBehavior.Never)
                    {
                        return(Authenticate(throwOnError, resource, PromptBehavior.Auto));
                    }
                }

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

                if (throwOnError)
                {
                    throw e;
                }

                IsAuthenticated = false;
                return(false);
            }
        }
        static async Task PostTodo()
        {
            // Get an access token from Azure AD using client credentials.
            // If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each.

            AuthenticationResult result = null;
            int  retryCount             = 0;
            bool retry = false;

            do
            {
                retry = false;
                try
                {   // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
                    result = await authContext.AcquireTokenAsync(todoListResourceId, certCred);
                }
                catch (Exception ex)
                {
                    AdalException exc = ex as AdalException;
                    if (exc.ErrorCode == "temporarily_unavailable")
                    {
                        retry = true;
                        retryCount++;
                        Thread.Sleep(3000);
                    }

                    Console.WriteLine(
                        String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n",
                                      DateTime.Now.ToString(),
                                      ex.ToString(),
                                      retry.ToString()));
                }
            } while ((retry == true) && (retryCount < 3));

            if (result == null)
            {
                Console.WriteLine("Canceling attempt to contact To Do list service.\n");
                return;
            }

            //
            // Post an item to the To Do list service.
            //

            // Add the access token to the authorization header of the request.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode To Do item and POST to the todo list web api.
            string timeNow = DateTime.Now.ToString();

            Console.WriteLine("Posting to To Do list at {0}", timeNow);
            string              todoText = "Task at time: " + timeNow;
            HttpContent         content  = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", todoText) });
            HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content);

            if (response.IsSuccessStatusCode == true)
            {
                Console.WriteLine("Successfully posted new To Do item:  {0}\n", todoText);
            }
            else
            {
                Console.WriteLine("Failed to post a new To Do item\nError:  {0}\n", response.ReasonPhrase);
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Wrap an exception thrown by the ADAL library.  This prevents client dependencies on a particular version fo ADAL.
 /// </summary>
 /// <param name="message">The exception message</param>
 /// <param name="innerException">The inner AdalException with additional details</param>
 internal AuthenticationException(string message, AdalException innerException) :
     base(string.Format(CultureInfo.CurrentCulture, message, innerException.Message), innerException)
 {
 }
        // Add a new ToDo in the list of the current user.
        // If there is no valid token available, obtain a new one.
        static void AddTodo()
        {
            #region Obtain token
            AuthenticationResult result = null;
            // first, try to get a token silently
            try
            {
                result = authContext.AcquireTokenSilentAsync(todoListResourceId, clientId).Result;
            }
            catch (AggregateException exc)
            {
                AdalException ex = exc.InnerException as AdalException;

                // There is no token in the cache; prompt the user to sign-in.
                if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently")
                {
                    // An unexpected error occurred.
                    ShowError(ex);
                    return;
                }
            }

            if (result == null)
            {
                UserCredential uc = TextualPrompt();
                // if you want to use Windows integrated auth, comment the line above and uncomment the one below
                // UserCredential uc = new UserCredential();
                try
                {
                    result = authContext.AcquireTokenAsync(todoListResourceId, clientId, uc).Result;
                }
                catch (Exception ee)
                {
                    ShowError(ee);
                    return;
                }
            }

            #endregion

            #region Call Web API
            Console.WriteLine("Enter new todo description >");
            string descr = Console.ReadLine();

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", descr) });

            var response = httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("New ToDo '{0}' successfully added.", descr);
            }
            #endregion

            #region Error handling
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    // If the To Do list service returns access denied, clear the token cache and have the user sign-in again.
                    Console.WriteLine("Sorry, you don't have access to the To Do Service. You might need to sign up.");
                    authContext.TokenCache.Clear();
                }
                else
                {
                    Console.WriteLine("Sorry, an error occurred accessing your To Do list.  Please try again.");
                }
            }
            #endregion
        }
 /// <summary>
 /// Wrap an exception thrown by the ADAL library.  This prevents client dependencies on a particular version fo ADAL.
 /// </summary>
 /// <param name="message">The exception message</param>
 /// <param name="innerException">The inner AdalException with additional details</param>
 internal AuthenticationException(string message, AdalException innerException) :
     base(string.Format(CultureInfo.CurrentCulture, message, (innerException == null)? string.Empty : innerException?.Message), innerException)
 {
 }
 internal AdalAuthException(string message, AdalException innerException) : base(message, innerException)
 {
 }