/// <summary>
        /// Performs the authentication.
        /// </summary>
        /// <returns>
        /// The authentication result.
        /// </returns>
        public async Task<AuthenticationResult> Authenticate()
        {
            var result = new AuthenticationResult()
            {
                Success = true
            };

            var github = new GitHubClient(new Octokit.ProductHeaderValue("BadgesSharp"));
            github.Credentials = new Credentials(m_accessToken);
            Octokit.Repository repo;

            try
            {
                repo = await github.Repository.Get(m_repositoryOwner, m_repositoryName);

                if (!repo.Permissions.Push)
                {
                    result.Success = false;
                    result.Message = "You do not have push permission to {0}/{1}".With(m_repositoryOwner, m_repositoryName);
                }
            }
            catch (ApiException ex)
            {
                result.Success = false;

                if (ex.Message.Equals("Not Found", StringComparison.OrdinalIgnoreCase))
                {
                    result.Message = "Your personal access token is valid, but it does not have access to {0}/{1}. If you're trying to generate a badge to a private repository, you need to check the scope \"repo\" at https://github.com/settings/tokens".With(m_repositoryOwner, m_repositoryName);
                }
                else
                {
                    result.Message = "Your personal access token seems be invalid. Certified you've generated it on https://github.com/settings/tokens: {0}".With(ex.Message);
                }
            }

            return result;
        }
        public static void SignInComplete(AuthenticationResult aresult, Context context)
        {
            App.AuthenticationContext = authContext;

            context.StartActivity(typeof(IncidentActivity));
            ((Activity)context).Finish();
        }
Beispiel #3
0
        public static void Init()
        {
            Authenticating = false;
            AuthenticationResult = AuthenticationResult.Success;

            Application.Library.RegisterEventHandler(ClientEvent.Authenticated, OnAuthenticated);
            Application.Library.RegisterEventHandler(ClientEvent.AuthenticationFailed, OnAuthenticationFailed);
        }
Beispiel #4
0
 private void Client_AuthenticationFailed(AuthenticationResult result)
 {
     if (result == AuthenticationResult.InvalidUser || result == AuthenticationResult.InvalidPassword
         || result == AuthenticationResult.InvalidVersion || result == AuthenticationResult.Banned
         || result == AuthenticationResult.EmailNotActivated)
     {
         IsEnabled = false;
         _reconnecting = false;
     }
 }
 [Ignore] // placeholder for actual test
 public void AuthenticateTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     NoneAuthenticationMethod target = new NoneAuthenticationMethod(username); // TODO: Initialize to an appropriate value
     Session session = null; // TODO: Initialize to an appropriate value
     AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
     AuthenticationResult actual;
     actual = target.Authenticate(session);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Beispiel #6
0
        private byte[] AuthResponse(AuthenticationResult result, Account account)
        {
            using (var builder = this.PacketFactory.CreatePacket("Authentication"))
            {
                builder.WriteInt32(result);

                builder.WriteInt16(0x0000);

                if (result == AuthenticationResult.Success)
                {
                    builder.WriteInt32(account.AccountId);

                    if (this.State == AuthClientState.SetGender)
                    {
                        builder.WriteByte(AuthOperationType.GenderSelect);
                    }
                    else if (this.State == AuthClientState.SetPin)
                    {
                        builder.WriteByte(AuthOperationType.PinSelect);
                    }
                    else
                    {
                        builder.WriteByte(account.Gender);
                    }

                    // Enables commands like /c, /ch, /m, /h (etc.), but disables trading
                    builder.WriteBoolean(account.IsGameMaster);

                    // Seems like 0x80 is a "MWLB" account - I doubt it... it disables attacking and allows GM fly
                    // 0x40, 0x20 (and probably 0x10, 0x8, 0x4, 0x2, and 0x1) don't appear to confer any particular benefits, restrictions, or functionality
                    // (Although I didn't test client GM commands or anything of the sort)
                    builder.WriteByte(account.IsGameMaster ? 0x80 : 0x00);

                    builder.WriteBoolean(account.IsGameMaster || account.IsGameMasterHelper);

                    builder.WriteLengthString(account.UserName);

                    builder.WriteByte(2);

                    // TODO: quiet ban support?
                    //builder.WriteByte(account.QuietBanReason);
                    builder.WriteByte(0);
                    //builder.WriteTimestamp(account.QuietBanTime);
                    builder.WriteInt64(0);

                    // TODO: Creation time
                    builder.WriteTimestamp(account.CreationTime);

                    builder.WriteInt32(0);
                }

                return builder.ToByteArray();
            }
        }
        public static OutgoingAuthenticationPacket BuildAuthenticationLogOnChallengeFailure(AuthenticationResult result, bool immediateDisconnect = false)
        {
            Contract.Requires(result != AuthenticationResult.Success && result != AuthenticationResult.SuccessSurvey);
            Contract.Ensures(Contract.Result<OutgoingAuthenticationPacket>() != null);

            var packet = new OutgoingAuthenticationPacket(GruntOpCode.AuthenticationLogOnChallenge);

            packet.Write(immediateDisconnect);
            packet.Write((byte)result);

            return packet;
        }
        private void Session_UserAuthenticationFailureReceived(object sender, MessageEventArgs<FailureMessage> e)
        {
            if (e.Message.PartialSuccess)
                this._authenticationResult = AuthenticationResult.PartialSuccess;
            else
                this._authenticationResult = AuthenticationResult.Failure;

            //  Copy allowed authentication methods
            this.AllowedAuthentications = e.Message.AllowedAuthentications.ToList();

            this._authenticationCompleted.Set();
        }
Beispiel #9
0
        private static void AuthenticateUsingCredentials(String p_Username, String p_Password)
        {
            if ((AuthenticationResult = Application.Library.User.Authenticate(p_Username, p_Password)) != AuthenticationResult.Success)
            {
                Authenticating = false;
                return;
            }

            // Store new session ID in database.
            using (var s_Db = Database.GetConnection())
                s_Db.Update(new CoreSetting() { Key = "gssess", Value = Application.Library.User.SessionID });

            Application.Library.Chat.Connect(true);
        }
        private void viewModel_OnAuthenticationStatusChanged(AuthenticationResult status)
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated == true && status == AuthenticationResult.OK)
            {
                Storyboard fadeOut = this.Resources["FadeOut"] as Storyboard;

                fadeOut.Completed += (object sender, EventArgs e) =>
                {
                    MainWindow main = new MainWindow();
                    MainViewModel ViewModelMain = new MainViewModel();
                    main.DataContext = ViewModelMain;
                    Application.Current.MainWindow = main.ParentOfType<Window>();
                    main.Show();
                    this.Close();
                };
                fadeOut.Begin();
            }
        }
        private async Task ProcessResponseAsync(AuthenticationResult authenticationResult, AuthMechanismProcessorStatus authMechanismProcessorStatus)
        {
            Mocks mocks = new Mocks();
            mocks.ServerBehaviour.Setup(
                b =>
                b.ValidateAuthenticationCredentialsAsync(mocks.Connection.Object, It.IsAny<AnonymousAuthenticationCredentials>()))
                .ReturnsAsync(authenticationResult);

            AnonymousMechanismProcessor anonymousMechanismProcessor = new AnonymousMechanismProcessor(mocks.Connection.Object);
            AuthMechanismProcessorStatus result = await anonymousMechanismProcessor.ProcessResponseAsync(null);

            Assert.Equal(authMechanismProcessorStatus, result);

            if (authenticationResult == AuthenticationResult.Success)
            {
                Assert.IsType(typeof(AnonymousAuthenticationCredentials), anonymousMechanismProcessor.Credentials);
            }
        }
Beispiel #12
0
        private static void AuthenticateUsingSession(String p_SessionID)
        {
            if ((AuthenticationResult = Application.Library.User.Authenticate(p_SessionID)) != AuthenticationResult.Success)
            {
                // Session-based authentication failed; retry with stored username and password.
                using (var s_Db = Database.GetConnection())
                {
                    var s_UsernameSetting = s_Db.SingleById<CoreSetting>("gsun");
                    var s_PasswordSetting = s_Db.SingleById<CoreSetting>("gspw");

                    AuthenticateUsingCredentials(s_UsernameSetting.Value, s_PasswordSetting.Value);
                }

                return;
            }

            Application.Library.Chat.Connect(true);
        }
 /// <summary>
 /// This method is called from a method if the user is not properly signed in yet
 /// and to check if the user can be authenticated
 /// (also checks for an active internet connection)
 /// </summary>
 private async Task<bool> TrySilentAuthentication()
 {
     try
     {
         // Here, we try to get an access token to call the service without invoking any UI prompt.  PromptBehavior.Never forces
         // ADAL to throw an exception if it cannot get a token silently.
         _authResult = await _authContext.AcquireTokenAsync(_scopes, null, Settings.ClientId, redirectUri, new PlatformParameters(PromptBehavior.Never, null));
         return true;
     }
     catch (AdalException ex)
     {
         // ADAL couldn't get a token silently, so show the user a message
         // and let them click the Sign-In button.
         if (ex.ErrorCode == "user_interaction_required")
         {
             //Console.WriteLine("Please sign in first");
             var res = await SignIn();
             return res;
         }
         else
         {
             // In any other case, an unexpected error occurred.
             string message = ex.Message;
             if (ex.InnerException != null)
             {
                 message += "Inner Exception : " + ex.InnerException.Message;
             }
             Logger.WriteToLogFile(ex);
             return false;
         }
     }
     catch (Exception e)
     {
         Logger.WriteToLogFile(e);
         return false;
     }
 }
Beispiel #14
0
 private static void OnAuthenticationFailed(SharkEvent p_SharkEvent)
 {
     Authenticating = false;
     AuthenticationResult = AuthenticationResult.InternalError;
 }
        private async Task AddTodoItemAsync()
        {
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            //
            // Get an access token to call the To Do service.
            //
            AuthenticationResult result = null;

            try
            {
                result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId);

                this.SetUserName(result.UserInfo);
            }
            catch (AdalException ex)
            {
                // There is no access token in the cache, so prompt the user to sign-in.
                if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    MessageBox.Show("Please sign in first");
                    SignInButton.Content = signInString;
                }
                else
                {
                    // An unexpected error occurred.
                    string message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                    }

                    MessageBox.Show(message);
                }

                UserName.Content = Properties.Resources.UserNotSignedIn;

                return;
            }

            //
            // Call the To Do service.
            //

            // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode Todo item, to POST to the todo list web api.
            HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", TodoText.Text) });

            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                GetTodoList();
            }
            else
            {
                MessageBox.Show("An error occurred : " + response.ReasonPhrase);
            }
        }
Beispiel #16
0
        public async Task NoCacheLookupAsync()
        {
            MyReceiver myReceiver = new MyReceiver();

            using (MockHttpAndServiceBundle harness = CreateTestHarness(telemetryCallback: myReceiver.HandleTelemetryEvents))
            {
                TokenCache cache                = new TokenCache(harness.ServiceBundle, false);
                string     clientInfo           = MockHelpers.CreateClientInfo();
                string     homeAccountId        = ClientInfo.CreateFromJson(clientInfo).ToAccountIdentifier();
                MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)),
                    clientInfo,
                    homeAccountId);

                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;
                ((ITokenCacheInternal)cache).Accessor.SaveAccessToken(atItem);

                MockWebUI ui = new MockWebUI()
                {
                    MockResult = AuthorizationResult.FromUri(TestConstants.AuthorityHomeTenant + "?code=some-code")
                };

                MsalMockHelpers.ConfigureMockWebUI(harness.ServiceBundle.PlatformProxy, ui);

                MockInstanceDiscoveryAndOpenIdRequest(harness.HttpManager);

                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityHomeTenant);

                AuthenticationRequestParameters parameters = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant,
                    TestConstants.s_scope,
                    cache,
                    extraQueryParameters: new Dictionary <string, string>
                {
                    { "extra", "qp" }
                });
                parameters.RedirectUri = new Uri("some://uri");
                parameters.LoginHint   = TestConstants.DisplayableId;
                AcquireTokenInteractiveParameters interactiveParameters = new AcquireTokenInteractiveParameters
                {
                    Prompt = Prompt.SelectAccount,
                    ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(),
                };

                InteractiveRequest request = new InteractiveRequest(
                    parameters,
                    interactiveParameters);

                AuthenticationResult result = await request.RunAsync().ConfigureAwait(false);

                Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count());
                Assert.AreEqual(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(result.AccessToken, "some-access-token");

                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.UserCancelledKey] == "false"));
                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("api_event") &&
                        anEvent[ApiEvent.PromptKey] == "select_account"));
                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.AccessDeniedKey] == "false"));
            }
        }
Beispiel #17
0
	public static async Task<string> SendGraphGetRequest(AuthenticationResult authResult, string api, string query, string tenant, string adminClientId, string adminClientSecret)
	{
		var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
		var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(adminClientId, adminClientSecret);

		// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
		// AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so.
		//var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));

		//// We don't care which policy is used to access the TaskService, so let's use the most recent policy
		//var mostRecentPolicy = authTicket.Identity.FindFirst(AcrClaimType).Value;
		//var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy);

		//// First, use ADAL to acquire a token using the app's identity (the credential)
		//// The first parameter is the resource we want an access_token for; in this case, the Graph API.
		var result = authContext.AcquireToken("https://graph.windows.net", credential);

		// For B2C user managment, be sure to use the beta Graph API version.
		var http = new HttpClient();
		var url = "https://graph.windows.net/" + tenant + api + "?" + "api-version=beta";
		if (!string.IsNullOrEmpty(query))
		{
			url += "&" + query;
		}

		//Console.ForegroundColor = ConsoleColor.Cyan;
		//Console.WriteLine("GET " + url);
		//Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
		//Console.WriteLine("");

		// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
		var request = new HttpRequestMessage(HttpMethod.Get, url);
		//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token);
		request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
		var response = await http.SendAsync(request);

		if (!response.IsSuccessStatusCode)
		{
			string error = await response.Content.ReadAsStringAsync();
			object formatted = JsonConvert.DeserializeObject(error);
			throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
		}

		//Console.ForegroundColor = ConsoleColor.Green;
		//Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
		//Console.WriteLine("");

		return await response.Content.ReadAsStringAsync();
	}
Beispiel #18
0
		private async Task<AuthenticationResult> Authenticate(AuthenticationProvider provider)
		{
			var result = new AuthenticationResult();

			try
			{
				result.UserId = await this.MobileServices.AuthenticateAsync(this, provider);
			}
			catch (InvalidOperationException ex)
			{
				result.Error = ex;
			}

			return result;
		}
        private void Session_UserAuthenticationSuccessReceived(object sender, MessageEventArgs<SuccessMessage> e)
        {
            this._authenticationResult = AuthenticationResult.Success;

            this._authenticationCompleted.Set();
        }
Beispiel #20
0
        private static async Task RunAsync()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication
            bool isUsingClientSecret = AppUsesClientSecret(config);

            // Even if this is a console application here, a daemon application is a confidential client application
            IConfidentialClientApplication app;

            if (isUsingClientSecret)
            {
                app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                      .WithClientSecret(config.ClientSecret)
                      .WithAuthority(new Uri(config.Authority))
                      .WithExperimentalFeatures() // for PoP
                      .Build();
            }

            else
            {
                X509Certificate2 certificate = ReadCertificate(config.CertificateName);
                app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                      .WithCertificate(certificate)
                      .WithAuthority(new Uri(config.Authority))
                      .Build();
            }

            // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
            // application permissions need to be set statically (in the portal or by PowerShell), and then granted by
            // a tenant administrator
            string[] scopes = new string[] { config.TodoListScope };

            AuthenticationResult result = null;
            string popUri = $"{config.TodoListBaseAddress}/api/todolist";

            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .WithProofOfPossession(new PoPAuthenticationConfiguration(new Uri(popUri))
                {
                    HttpMethod = HttpMethod.Get
                })
                         .ExecuteAsync();

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Token acquired \n");
                Console.ResetColor();
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Scope provided is not supported");
                Console.ResetColor();
            }

            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                await apiCaller.CallWebApiAndProcessResultASync(popUri, result, Display);
            }
        }
Beispiel #21
0
        private async Task StartAuthenticationAsync()
        {
            if (Authentication.IsWindowsAuthentication)
            {
                this.IsLoginFormAvailable = false;
                this.AuthenticationResult = await Authentication.LoginWithWindowsAuthenticationAsync();

                this.RaiseOnAuthenticationStatusChanged(this.AuthenticationResult);
                if (this.AuthenticationResult != Insyston.Operations.Security.Enums.AuthenticationResult.OK)
                {
                    this.IsLoginFormAvailable = true;
                }
            }
            else
            {
                this.IsLoginFormAvailable = true;
            }
        }
        public void AuthenticationTest(string username, string password, AuthenticationResult expectedResult)
        {
            AuthenticationResult result = this._service.Authenticate(username, password);

            Assert.Equal(expectedResult, result);
        }
Beispiel #23
0
 private void OnUserAuthenticatedEventPublished(AuthenticationResult authResult)
 {
     NavigationService.NavigateAsync("/NavigationPage/MainPage", ("authResult", authResult));
 }
 /// <summary>
 /// Gets a <see cref="SecurityToken"/> for the given audience and duration.
 /// </summary>
 /// <param name="appliesTo">The URI which the access token applies to</param>
 /// <param name="timeout">The time span that specifies the timeout value for the message that gets the security token</param>
 /// <returns><see cref="SecurityToken"/></returns>
 public override async Task <SecurityToken> GetTokenAsync(string appliesTo, TimeSpan timeout)
 {
     AuthenticationResult authResult = _authType switch
     {
Beispiel #25
0
        private async Task <AuthenticationResult> AcquireTokenAsync(bool forceRefresh = false)
        {
            bool acquired = false;

            if (forceRefresh)
            {
                authContext.TokenCache.Clear();
            }

            try
            {
                // The ADAL client team recommends limiting concurrency of calls. When the Token is in cache there is never
                // contention on this semaphore, but when tokens expire there is some. However, after measuring performance
                // with and without the semaphore (and different configs for the semaphore), not limiting concurrency actually
                // results in higher response times overall. Without the use of this semaphore calls to AcquireTokenAsync can take up
                // to 5 seconds under high concurrency scenarios.
#pragma warning disable VSTHRD103 // Call async methods when in an async method
                acquired = tokenRefreshSemaphore.Wait(SemaphoreTimeout);
#pragma warning restore VSTHRD103 // Call async methods when in an async method

                // If we are allowed to enter the semaphore, acquire the token.
                if (acquired)
                {
                    // Acquire token async using MSAL.NET
                    // https://github.com/AzureAD/azure-activedirectory-library-for-dotnet
                    // Given that this is a ClientCredential scenario, it will use the cache without the
                    // need to call AcquireTokenSilentAsync (which is only for user credentials).
                    // Scenario details: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Client-credential-flows#it-uses-the-application-token-cache
                    AuthenticationResult authResult = null;

                    // Password based auth
                    if (clientCredential != null)
                    {
                        authResult = await authContext.AcquireTokenAsync(authConfig.Scope, this.clientCredential).ConfigureAwait(false);
                    }

                    // Certificate based auth
                    else if (clientCertificate != null)
                    {
                        authResult = await authContext.AcquireTokenAsync(authConfig.Scope, clientCertificate, sendX5c : this.clientCertSendX5c).ConfigureAwait(false);
                    }

                    // This means we acquired a valid token successfully. We can make our retry policy null.
                    // Note that the retry policy is set under the semaphore so no additional synchronization is needed.
                    if (currentRetryPolicy != null)
                    {
                        currentRetryPolicy = null;
                    }

                    return(authResult);
                }
                else
                {
                    // If the token is taken, it means that one thread is trying to acquire a token from the server.
                    // If we already received information about how much to throttle, it will be in the currentRetryPolicy.
                    // Use that to inform our next delay before trying.
                    throw new ThrottleException()
                          {
                              RetryParams = currentRetryPolicy
                          };
                }
            }
            catch (Exception ex)
            {
                // If we are getting throttled, we set the retry policy according to the RetryAfter headers
                // that we receive from the auth server.
                // Note that the retry policy is set under the semaphore so no additional synchronization is needed.
                if (IsAdalServiceUnavailable(ex))
                {
                    currentRetryPolicy = ComputeAdalRetry(ex);
                }

                throw;
            }
            finally
            {
                // Always release the semaphore if we acquired it.
                if (acquired)
                {
                    ReleaseSemaphore();
                }
            }
        }
        private async void AddTodoItem(object sender, RoutedEventArgs e)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (!accounts.Any())
            {
                MessageBox.Show("Please sign in first");
                return;
            }
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            // Get an access token to call the To Do service.
            AuthenticationResult result = null;

            try
            {
                result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                Dispatcher.Invoke(() =>
                {
                    SetUserName(result.Account);
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                });
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                MessageBox.Show("Please re-sign");
                SignInButton.Content = SignInString;
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }

                Dispatcher.Invoke(() =>
                {
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                    MessageBox.Show("Unexpected error: " + message);
                });


                return;
            }

            //
            // Call the To Do service.
            //

            // Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do service.
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode Todo item, to POST to the todo list web api.
            TodoItem todoItem = null;

            Dispatcher.Invoke(() =>
            {
                todoItem = new TodoItem()
                {
                    Title = TodoText.Text
                };
            });

            string        json    = JsonConvert.SerializeObject(todoItem);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            // Call the To Do list service.

            HttpResponseMessage response = await _httpClient.PostAsync(TodoListApiAddress, content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                GetTodoList();
            }
            else
            {
                await DisplayErrorMessage(response);
            }
        }
        [WorkItem(695)] // Fix for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/695
        public void AcquireTokenSilentForceRefreshFalseMultipleTenantsTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();

                // PopulateCache() creates two access tokens
                _tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        MsalTestConstants.UniqueId,
                        MsalTestConstants.DisplayableId,
                        MsalTestConstants.Scope.ToArray())
                });

                Task <AuthenticationResult> task = app
                                                   .AcquireTokenSilent(
                    MsalTestConstants.Scope.ToArray(),
                    new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null))
                                                   .WithAuthority(MsalTestConstants.AuthorityCommonTenant)
                                                   .WithForceRefresh(false)
                                                   .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(MsalTestConstants.DisplayableId, result.Account.Username);
                Assert.AreEqual(MsalTestConstants.Scope.ToArray().AsSingleString(), result.Scopes.AsSingleString());

                Assert.AreEqual(2, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count());

                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityGuidTenant2);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        MsalTestConstants.UniqueId,
                        MsalTestConstants.DisplayableId,
                        MsalTestConstants.Scope.ToArray())
                });

                // Same user, scopes, clientId, but different authority
                // Should result in new AccessToken, but same refresh token
                Task <AuthenticationResult> task2 = app
                                                    .AcquireTokenSilent(
                    MsalTestConstants.Scope.ToArray(),
                    new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null))
                                                    .WithAuthority(MsalTestConstants.AuthorityGuidTenant2)
                                                    .WithForceRefresh(false)
                                                    .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result2 = task2.Result;
                Assert.IsNotNull(result2);
                Assert.AreEqual(MsalTestConstants.DisplayableId, result2.Account.Username);
                Assert.AreEqual(MsalTestConstants.Scope.ToArray().AsSingleString(), result2.Scopes.AsSingleString());

                Assert.AreEqual(3, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count());

                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityGuidTenant);

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        MsalTestConstants.UniqueId,
                        MsalTestConstants.DisplayableId,
                        MsalTestConstants.Scope.ToArray())
                });

                // Same user, scopes, clientId, but different authority
                // Should result in new AccessToken, but same refresh token
                Task <AuthenticationResult> task3 = app
                                                    .AcquireTokenSilent(
                    MsalTestConstants.Scope.ToArray(),
                    new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null))
                                                    .WithAuthority(MsalTestConstants.AuthorityGuidTenant)
                                                    .WithForceRefresh(false)
                                                    .ExecuteAsync(CancellationToken.None);

                AuthenticationResult result3 = task3.Result;
                Assert.IsNotNull(result3);
                Assert.AreEqual(MsalTestConstants.DisplayableId, result3.Account.Username);
                Assert.AreEqual(MsalTestConstants.Scope.ToArray().AsSingleString(), result3.Scopes.AsSingleString());

                Assert.AreEqual(4, app.UserTokenCacheInternal.Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(1, app.UserTokenCacheInternal.Accessor.GetAllRefreshTokens().Count());
            }
        }
Beispiel #28
0
        /// <summary>
        /// Uses a graph call to return the UserId for a specified UPN
        /// </summary>
        /// <param name="user">The User Principal Name.</param>
        /// <returns>The Azuer UserId.</returns>
        public static string GetUserIdFromUpn(string user, string graphURI, string schemaVersion, AuthenticationResult authenticationResult)
        {
            string         url = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/users?$filter=userPrincipalName eq '{2}'", graphURI, schemaVersion, user);
            HttpWebRequest request;

            request = CreateWebRequest(url, authenticationResult);

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string responseMessage = string.Empty;
                    using (StreamReader rs = new StreamReader(response.GetResponseStream()))
                    {
                        responseMessage = rs.ReadToEnd();
                    }

                    User userObj = SerializationHelpers.DeserializeUser(responseMessage);
                    return(userObj.Id);
                }
                else
                {
                    throw new InvalidOperationException(response.StatusDescription);
                }
            }
        }
Beispiel #29
0
		/// <summary>
		/// Check if authentication succeeded after user is redirected back from the service provider.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// An instance of <see cref="AuthenticationResult" /> containing authentication result.
		/// </returns>
		public virtual async Task<AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, CancellationToken cancellationToken = default(CancellationToken)) {
			AccessTokenResponse response = await this.WebWorker.ProcessUserAuthorizationAsync(context, cancellationToken);
			if (response == null) {
				return AuthenticationResult.Failed;
			}

			AuthenticationResult result = await this.VerifyAuthenticationCoreAsync(response, cancellationToken);
			if (result.IsSuccessful && result.ExtraData != null) {
				// add the access token to the user data dictionary just in case page developers want to use it
				var wrapExtraData = new NameValueCollection(result.ExtraData);
				wrapExtraData["accesstoken"] = response.AccessToken.Token;
				wrapExtraData["accesstokensecret"] = response.AccessToken.Secret;

				AuthenticationResult wrapResult = new AuthenticationResult(
					result.IsSuccessful,
					result.Provider,
					result.ProviderUserId,
					result.UserName,
					wrapExtraData);

				result = wrapResult;
			}

			return result;
		}
        private static async Task <UserProfile> CallGraphAPIOnBehalfOfUser()
        {
            UserProfile          profile     = null;
            string               accessToken = null;
            AuthenticationResult result      = null;

            //
            // Use ADAL to get a token On Behalf Of the current user.  To do this we will need:
            //      The Resource ID of the service we want to call.
            //      The current user's access token, from the current request's authorization header.
            //      The credentials of this application.
            //      The username (UPN or email) of the user calling the API
            //
            ClientCredential clientCred = new ClientCredential(clientId, appKey);
            var    bootstrapContext     = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
            string userName             = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null?ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;

            string        userAccessToken = bootstrapContext.Token;
            UserAssertion userAssertion   = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

            string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
            string userId    = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            AuthenticationContext authContext = new AuthenticationContext(authority, new DbTokenCache(userId));

            // In the case of a transient error, retry once after 1 second, then abandon.
            // Retrying is optional.  It may be better, for your application, to return an error immediately to the user and have the user initiate the retry.
            bool retry      = false;
            int  retryCount = 0;

            do
            {
                retry = false;
                try
                {
                    result = await authContext.AcquireTokenAsync(graphResourceId, clientCred, userAssertion);

                    accessToken = result.AccessToken;
                }
                catch (AdalException ex)
                {
                    if (ex.ErrorCode == SERVICE_UNAVAILABLE)
                    {
                        // Transient error, OK to retry.
                        retry = true;
                        retryCount++;
                        Thread.Sleep(1000);
                    }
                }
            } while ((retry == true) && (retryCount < 2));

            if (accessToken == null)
            {
                // An unexpected error occurred.
                return(null);
            }

            //
            // Call the Graph API and retrieve the user's profile.
            //
            string requestUrl = String.Format(
                CultureInfo.InvariantCulture,
                graphUserUrl,
                HttpUtility.UrlEncode(tenant));
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            //
            // Return the user's profile.
            //
            if (response.IsSuccessStatusCode)
            {
                string responseString = await response.Content.ReadAsStringAsync();

                profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                return(profile);
            }

            // An unexpected error occurred calling the Graph API.  Return a null profile.
            return(null);
        }
        public async Task<AuthenticationResult> AuthenticateAsync(AuthNProviderType providerType,
                                                                  IAuthNProviderSettings providerSettings)
        {
            // try without sending AMS Application key for now
            _mobileSvcsClient = new 
                MobileServiceClient(providerSettings.UrlToAuthenticationProvider);

            // default to MS account if whatever passed in is a no go
            // TODO: See Azure Mobile GitHub to see how they check for invalid Enum values
            var azmobProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;

            // see which Azure Mobile Services Authentication Provider they want to use
            switch (providerType)
            {
                case AuthNProviderType.Google:
                    azmobProvider = MobileServiceAuthenticationProvider.Google;
                    break;
                case AuthNProviderType.Facebook:
                    azmobProvider = MobileServiceAuthenticationProvider.Facebook;
                    break;
                case AuthNProviderType.Twitter:
                    azmobProvider = MobileServiceAuthenticationProvider.Twitter;
                    break;
                case AuthNProviderType.Microsoft:
                    azmobProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;
                    break;
                default:
                    break;
            }

            try
            {
                await _mobileSvcsClient.LoginAsync(azmobProvider);

                // TODO: How do I want to use User Profile Stuff here?
                // TODO: I will doouble set stff to see how it feels to use each

                var userProfile = await LoadUserProfile();

                var authResult = new AuthenticationResult
                {
                    ProviderName = _mobileSvcsClient.ToString(),
                    IdentityString = _mobileSvcsClient.CurrentUser.UserId,
                    MobileServicesUserToken = _mobileSvcsClient.CurrentUser.MobileServiceAuthenticationToken
                };

                return authResult;
            }
            catch (InvalidOperationException iop)
            {
                // TODO: if I try to login to Twitter and click back button on WP8
                // TODO: then System.InvalidOperationException is thrown but is NOT caught in Login VM!??  Why?
                // TODO: Must the try catch be inside here in the platform-specific authprovider?
                // TODO: Seems like that is the case, so leave it?

                // TODO: Do something useful
                //user cancelled so try again
                //MessageBox.Show("You must login to access the application.", "Please try again", MessageBoxButton.OK);
                Debug.WriteLine(
                    "AuthenticationProvider:InvalidOpException: You must login to access the application.");
            }
            catch (Exception ex)
            {
                // TODO: Do something useful
                //MessageBox.Show("We were not able to log you in, make sure you are connected to the internet and try again.", "Login failed", MessageBoxButton.OK);
                Debug.WriteLine(
                    "AuthenticationProvider:Exception: not able to log you in, make sure you are connected to the internet.");
            }
            finally
            {
                Debug.WriteLine("AuthenticationProvider:AuthenticateAsync: finally in try catch...got here!");
            }

            // TODO: how do I want to handle?
            // if I got here then something bad happened
            // TODO: Something besides null?

            return null;
        }
Beispiel #32
0
 private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
 {
     // Upon successful sign in, get the access token & cache it using MSAL
     IConfidentialClientApplication clientApp = MsalAppBuilder.BuildConfidentialClientApplication();
     AuthenticationResult           result    = await clientApp.AcquireTokenByAuthorizationCode(new[] { "Mail.Read" }, context.Code).ExecuteAsync();
 }
 static IPrincipal CreatePrincipal(AuthenticationResult.Success success, IAuthenticationScheme scheme)
 {
     var identity = new GenericIdentity(success.Username, scheme.Name);
     return new GenericPrincipal(identity, success.Roles);
 }
Beispiel #34
0
 public MsalToken(AuthenticationResult authenticationResult)
     : this(authenticationResult.AccessToken)
 {
 }
Beispiel #35
0
 public AuthenticationResponse(AuthenticationResult result) : this()
 {
     Result = result;
 }
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            Scheduler.RunTask(async() =>
            {
                MgmtAccount account = new MgmtAccount();
                string applicationId;

                if (!string.IsNullOrEmpty(CertificateThumbprint))
                {
                    account.SetProperty(MgmtAccountPropertyType.CertificateThumbprint, CertificateThumbprint);
                }

                if (ParameterSetName.Equals(RefreshTokenParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    if (Credential != null)
                    {
                        account.ObjectId = Credential.UserName;
                        account.SetProperty(MgmtAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
                        applicationId = Credential.UserName;
                    }
                    else
                    {
                        applicationId = ApplicationId;
                    }
                }
                else if (ParameterSetName.Equals(ServicePrincipalCertificateParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    account.SetProperty(MgmtAccountPropertyType.ApplicationId, ApplicationId);
                    account.Type  = AccountType.Certificate;
                    applicationId = ApplicationId;
                }
                else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase))
                {
                    account.ObjectId = Credential.UserName;
                    account.SetProperty(MgmtAccountPropertyType.ServicePrincipalSecret, Credential.Password.ConvertToString());
                    account.Type  = AccountType.ServicePrincipal;
                    applicationId = ApplicationId;
                }
                else
                {
                    account.Type  = AccountType.User;
                    applicationId = ApplicationId;
                }

                if (UseAuthorizationCode.IsPresent)
                {
                    account.SetProperty(MgmtAccountPropertyType.UseAuthCode, "true");
                }

                if (UseDeviceAuthentication.IsPresent)
                {
                    account.SetProperty(MgmtAccountPropertyType.UseDeviceAuth, "true");
                }

                if (!string.IsNullOrEmpty(RefreshToken))
                {
                    account.SetProperty(MgmtAccountPropertyType.RefreshToken, RefreshToken);
                }

                account.SetProperty(MgmtAccountPropertyType.ApplicationId, applicationId);
                account.Tenant = string.IsNullOrEmpty(Tenant) ? "organizations" : Tenant;

                AuthenticationResult authResult = await MgmtSession.Instance.AuthenticationFactory.AuthenticateAsync(
                    account,
                    MgmtEnvironment.PublicEnvironments[Environment],
                    Scopes,
                    Message,
                    CancellationToken).ConfigureAwait(false);

                AuthResult result = new AuthResult(
                    authResult.AccessToken,
                    authResult.IsExtendedLifeTimeToken,
                    authResult.UniqueId,
                    authResult.ExpiresOn,
                    authResult.ExtendedExpiresOn,
                    authResult.TenantId,
                    authResult.Account,
                    authResult.IdToken,
                    authResult.Scopes,
                    authResult.CorrelationId);

                byte[] cacheData = null;

                if (MgmtSession.Instance.TryGetComponent(ComponentKey.TokenCache, out IMgmtTokenCache tokenCache))
                {
                    cacheData = tokenCache.GetCacheData();

                    if (cacheData?.Length > 0)
                    {
                        IEnumerable <string> knownPropertyNames = new[] { "AccessToken", "RefreshToken", "IdToken", "Account", "AppMetadata" };

                        JObject root = JObject.Parse(Encoding.UTF8.GetString(cacheData, 0, cacheData.Length));

                        IDictionary <string, JToken> known = (root as IDictionary <string, JToken>)
                                                             .Where(kvp => knownPropertyNames.Any(p => string.Equals(kvp.Key, p, StringComparison.OrdinalIgnoreCase)))
                                                             .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                        IDictionary <string, TokenCacheItem> tokens = new Dictionary <string, TokenCacheItem>();

                        if (known.ContainsKey("RefreshToken"))
                        {
                            foreach (JToken token in root["RefreshToken"].Values())
                            {
                                if (token is JObject j)
                                {
                                    TokenCacheItem item = new TokenCacheItem
                                    {
                                        ClientId       = ExtractExistingOrEmptyString(j, "client_id"),
                                        CredentialType = ExtractExistingOrEmptyString(j, "credential_type"),
                                        Environment    = ExtractExistingOrEmptyString(j, "environment"),
                                        HomeAccountId  = ExtractExistingOrEmptyString(j, "home_account_id"),
                                        RawClientInfo  = ExtractExistingOrEmptyString(j, "client_info"),
                                        Secret         = ExtractExistingOrEmptyString(j, "secret")
                                    };

                                    tokens.Add($"{item.HomeAccountId}-{item.Environment}-RefreshToken-{item.ClientId}--", item);
                                }
                            }
                        }

                        if (authResult.Account != null)
                        {
                            string key = tokenCache.GetCacheKey(authResult);

                            if (tokens.ContainsKey(key))
                            {
                                result.RefreshToken = tokens[key].Secret;
                            }
                        }
                    }
                    else
                    {
                        WriteDebug("There was not any data in the token cache, so a refresh token could not be retrieved.");
                    }
                }
                else
                {
                    WriteDebug("Unable to find a registered token cache.");
                }

                WriteObject(result);
            });
        }
Beispiel #37
0
	//// Used for avoiding yellow-screen-of-death
	//private static Task AuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
	//{
	//    notification.HandleResponse();
	//    notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message);
	//    return Task.FromResult(0);
	//}

	public static async Task<string> GetUserByObjectId(AuthenticationResult authResult, string objectId, string tenant, string adminClientId, string adminClientSecret)
	{
		return await SendGraphGetRequest(authResult, "/users/" + objectId, null, tenant, adminClientId, adminClientSecret);
	}
 private void AssertTokenSource_IsIdP(
     AuthenticationResult result)
 {
     Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
 }
Beispiel #39
0
        private static void OnAuthenticated(SharkEvent p_SharkEvent)
        {
            Authenticating = false;
            AuthenticationResult = AuthenticationResult.Success;

            QueueManager.FetchCollectionSongs();

            if (QueueManager.CollectionSongs.Count < 2)
                return;

            BroadcastManager.CreateBroadcast();
        }
        public static OutgoingAuthenticationPacket BuildReconnectChallengeSuccess(BigInteger reconnectProof,
            AuthenticationResult result = AuthenticationResult.Success)
        {
            Contract.Requires(reconnectProof != null);
            Contract.Requires(reconnectProof.ByteLength == Password.MD5Length);
            Contract.Requires(result == AuthenticationResult.Success || result == AuthenticationResult.SuccessSurvey);
            Contract.Ensures(Contract.Result<OutgoingAuthenticationPacket>() != null);

            var packet = new OutgoingAuthenticationPacket(GruntOpCode.AuthenticationReconnectChallenge);

            packet.Write((byte)result);
            packet.Write(reconnectProof, Password.MD5Length);
            packet.Write(new byte[Password.MD5Length]); // HMAC seed for client file verification.

            return packet;
        }
        private async Task GetTodoListAsync(bool isAppStarting)
        {
            //
            // Get an access token to call the To Do service.
            //
            AuthenticationResult result = null;

            try
            {
                result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId);

                SignInButton.Content = clearCacheString;
                this.SetUserName(result.UserInfo);
            }
            catch (AdalException ex)
            {
                // There is no access token in the cache, so prompt the user to sign-in.
                if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    if (!isAppStarting)
                    {
                        MessageBox.Show("Please sign in to view your To-Do list");
                        SignInButton.Content = signInString;
                    }
                }
                else
                {
                    // An unexpected error occurred.
                    string message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                    }
                    MessageBox.Show(message);
                }

                UserName.Content = Properties.Resources.UserNotSignedIn;

                return;
            }

            // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do list service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "/api/todolist");

            if (response.IsSuccessStatusCode)
            {
                // Read the response and databind to the GridView to display To Do items.
                string s = await response.Content.ReadAsStringAsync();

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                List <TodoItem>      toDoArray  = serializer.Deserialize <List <TodoItem> >(s);

                TodoList.ItemsSource = toDoArray.Select(t => new { t.Title });
            }
            else
            {
                MessageBox.Show("An error occurred : " + response.ReasonPhrase);
            }

            return;
        }
Beispiel #42
0
        static void Main()
        {
            CancellationToken token = CancellationToken.None;

            GraphAuth            graphAuth = new GraphAuth("btcloud1");
            AuthenticationResult result    = null;

            try
            {
                result = graphAuth.GetAuthResult();
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
            }

            if (result != null)
            {
            }

            O365Graph graph = new O365Graph(graphAuth);

            int orgCount = 0;

            foreach (var orgs in graph.GetOrganizations(token))
            {
                orgCount += orgs.Count;
            }
            Trace.WriteLine($"Organization count: {orgCount}");

            int userCount = 0;

            foreach (var users in graph.GetUsers(token))
            {
                userCount += users.Count;
            }
            Trace.WriteLine($"User count: {userCount}");

            int dlCount = 0;

            foreach (var distributionGroups in graph.GetDistributionGroups(token))
            {
                dlCount += distributionGroups.Count;
            }
            Trace.WriteLine($"DistributionGroup count: {dlCount}");

            int groupCount = 0;

            foreach (List <Group> groups in graph.GetGroups(token))
            {
                groupCount += groups.Count;
            }
            Trace.WriteLine($"Group count: {groupCount}");

            int securityCount = 0;

            foreach (var securityGroups in graph.GetMailEnabledSecurityGroups(token))
            {
                securityCount += securityGroups.Count;
            }
            Trace.WriteLine($"SecurityGroup count: {securityCount}");

            int unifiedCount = 0;

            foreach (var specialGroups in graph.GetSpecialGroups("Unified", token))
            {
                unifiedCount += specialGroups.Count;
            }
            Trace.WriteLine($"UnifiedGroup count: {unifiedCount}");

            int probeUserCount = 0;

            foreach (var probeUsers in graph.FindUsersStartsWith("DisplayName", "MailProbe", token))
            {
                probeUserCount += probeUsers.Count;
            }
            Trace.WriteLine($"ProbeUserCount count: {probeUserCount}");
        }
 private void AssertTokenSource_IsCache(
     AuthenticationResult result)
 {
     Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
 }
        public static void GetUsersFromAD()
        {
            //if (HttpContext.Current.Cache["ADUSERS"] == null)
            IDatabase cache = MvcApplication.RedisCache.GetDatabase();
            var adUsers = cache.Get<List<ActiveDirectoryUser>>("ADUSERS");
            if (adUsers == null)
            {
                // Graph API Settings
                string graphResourceId = "https://graph.windows.net";
                string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
                string appPassword = ConfigurationManager.AppSettings["ida:Password"];
                Uri audienceUri = new Uri(ConfigurationManager.AppSettings["ida:AudienceUri"]);
                string tenant = audienceUri.Host;
                string Authority = String.Format("https://login.windows.net/{0}", tenant);

                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Authority);
                activeDirectoryUsers = new List<ActiveDirectoryUser>();
                ClientCredential credential = new ClientCredential(clientId, appPassword);
                AuthenticationResult result = null;
                List<User> userList = new List<User>();
                result = authContext.AcquireToken(graphResourceId, credential);

                //Setup Graph API connection and get a list of users 
                Guid ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings = new GraphSettings();
                graphSettings.ApiVersion = "2013-11-08";

                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                // Get results from all pages into a list 
                PagedResults<User> pagedResults = graphConnection.List<User>(null, new FilterGenerator());
                userList.AddRange(pagedResults.Results);
                while (!pagedResults.IsLastPage)
                {
                    pagedResults = graphConnection.List<User>(pagedResults.PageToken, new FilterGenerator());
                    userList.AddRange(pagedResults.Results);
                }
                foreach (var u in userList)
                {
                    var adUser = new ActiveDirectoryUser();
                    adUser.Location = String.Format("{0},{1}", u.City, u.State);
                    adUser.FullName = u.GivenName + " " + u.Surname;
                    adUser.Position = u.JobTitle;
                    adUser.ActiveDirectoryId = u.UserPrincipalName;
                    adUser.ObjectId = u.ObjectId;

                    try
                    {
                        using (Stream ms = graphConnection.GetStreamProperty(u, GraphProperty.ThumbnailPhoto, "image/jpeg"))
                        {
                            if (ms != null)
                            {
                                byte[] b;
                                using (BinaryReader br = new BinaryReader(ms))
                                {
                                    b = br.ReadBytes((int)ms.Length);
                                }
                                adUser.ThumbnailPhoto = b;
                                // Retrieve via the controller
                                adUser.ImageUrl = String.Format("/AdImages/Details/{0}", adUser.ObjectId);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        adUser.ImageUrl = "/images/user-placeholder.png";
                    }
                    activeDirectoryUsers.Add(adUser);
                }
                // HttpContext.Current.Cache.Insert("ADUSERS", activeDirectoryUsers, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                cache.Set("ADUSERS", activeDirectoryUsers, TimeSpan.FromMinutes(5));

            }
            else
            {
                //activeDirectoryUsers = (List<ActiveDirectoryUser>)HttpContext.Current.Cache["ADUSERS"];
                activeDirectoryUsers = (List<ActiveDirectoryUser>)cache.Get("ADUSERS");
            }
        }
        public static OutgoingAuthenticationPacket BuildReconnectProofFailure(AuthenticationResult result)
        {
            Contract.Requires(result != AuthenticationResult.Success && result != AuthenticationResult.SuccessSurvey);
            Contract.Ensures(Contract.Result<OutgoingAuthenticationPacket>() != null);

            var packet = new OutgoingAuthenticationPacket(GruntOpCode.AuthenticationReconnectProof);

            packet.Write((byte)result);

            return packet;
        }
Beispiel #46
0
        private async Task <AuthenticationResult> GenerateAuthenticationResultForUserAsync(ApplicationUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_JwtSettings.Secret);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim("id", user.Id)
            };

            var userClaims = await _userManager.GetClaimsAsync(user);

            claims.AddRange(userClaims);

            var userRoles = await _userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                var role = await _roleManager.FindByNameAsync(userRole);

                if (role == null)
                {
                    continue;
                }
                var roleClaims = await _roleManager.GetClaimsAsync(role);

                foreach (var roleClaim in roleClaims)
                {
                    if (claims.Contains(roleClaim))
                    {
                        continue;
                    }

                    claims.Add(roleClaim);
                }
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Issuer             = _JwtSettings.Issuer,
                Audience           = _JwtSettings.Audience,
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.Add(_JwtSettings.TokenLifetime),
                SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var refreshToken = new RefreshToken
            {
                JwtId        = token.Id,
                UserId       = user.Id,
                CreationDate = DateTime.UtcNow,
                ExpiryDate   = DateTime.UtcNow.AddMonths(6)
            };

            _refreshToken.Insert(refreshToken);
            await _refreshToken.Commit();

            var TokenResponse = new AuthenticationResult
            {
                Success      = true,
                Token        = tokenHandler.WriteToken(token),
                RefreshToken = refreshToken.Token
            };

            await _responseCacheService.SetStringAsync(token.Id, tokenHandler.WriteToken(token), new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.Parse(_JwtSettings.TokenLifetime.ToString())
            });

            return(TokenResponse);
        }
        public static OutgoingAuthenticationPacket BuildAuthenticationLogOnProofFailure(AuthenticationResult result)
        {
            Contract.Requires(result != AuthenticationResult.Success && result != AuthenticationResult.SuccessSurvey);
            Contract.Ensures(Contract.Result<OutgoingAuthenticationPacket>() != null);

            var packet = new OutgoingAuthenticationPacket(GruntOpCode.AuthenticationLogOnProof);

            packet.Write((byte)result);

            if (result == AuthenticationResult.FailedUnknownAccount)
                packet.Write((short)0); // Unknown value.

            return packet;
        }
Beispiel #48
0
        /// <summary>
        /// Gets a list of <see cref="Group"/> objects that a given <see cref="User"/> is member of.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="User"/>.</param>
        /// <returns>A view with the list of <see cref="Group"/> objects.</returns>
        public ActionResult GetGroups(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result          = null;
            IList <Group>        groupMembership = new List <Group>();

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                //Setup Graph API connection and get a list of users
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                GraphObject graphUser = graphConnection.Get <User>(objectId);
                PagedResults <GraphObject> memberShip = graphConnection.GetLinkedObjects(graphUser, LinkProperty.MemberOf, null, 999);
                // users can be members of Groups and Roles
                // for this app, we will filter and only show Groups
                int count = 0;
                foreach (GraphObject graphObj in memberShip.Results)
                {
                    if (graphObj.ODataTypeName.Contains("Group"))
                    {
                        Group groupMember = (Group)memberShip.Results[count];
                        groupMembership.Add(groupMember);
                    }
                    ++count;
                }
                while (!memberShip.IsLastPage)
                {
                    memberShip = graphConnection.GetLinkedObjects(graphUser, LinkProperty.MemberOf, memberShip.PageToken, 999);
                    count      = 0;
                    foreach (GraphObject graphObj in memberShip.Results)
                    {
                        if (graphObj.ODataTypeName.Contains("Group"))
                        {
                            Group groupMember = (Group)memberShip.Results[count];
                            groupMembership.Add(groupMember);
                        }
                        ++count;
                    }
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            return(View(groupMembership));
        }
Beispiel #49
0
        private async Task LoginWithUserNameAndPasswordAsync()
        {
            try
            {
                this.AuthenticationResult = await Authentication.LoginWithFormAuthenticationAsync(this.UserName, this.Password);

                this.RaiseOnAuthenticationStatusChanged(this.AuthenticationResult);
                this.Validate();

                if (this.AuthenticationResult == Insyston.Operations.Security.Enums.AuthenticationResult.ExpiredPasswordWithGraceLogin || this.AuthenticationResult == Insyston.Operations.Security.Enums.AuthenticationResult.ExpiredPassword)
                {
                    this.IsChangePasswordFormAvailable = true;
                    this.UserID = Authentication.userID;
                    this.GraceLoginsLeft = Authentication.graceLoginsLeft;
                    this.EnforceChangePassword = this.AuthenticationResult == Insyston.Operations.Security.Enums.AuthenticationResult.ExpiredPassword;
                    this.EnforceChangePassword = this.GraceLoginsLeft <= 0;
                }
            }
            catch (VersionException ex)
            {
                ExceptionLogger.WriteLog(ex);
                this.AddManualValidationError("AuthenticationResult", ex.Message);
            }
            catch (Exception ex)
            {
                ExceptionLogger.WriteLog(ex);
                this.AddManualValidationError("AuthenticationResult", "Unexpected Error while trying to Login.\nThe error has been logged into the System, Please contact your System Administrator.");
            }
        }
Beispiel #50
0
        public SharePointFileManager(string serverAppIdUri,
                                     string odataUri,
                                     string webname,
                                     string aadTenantId,
                                     string clientId,
                                     string certFileName,
                                     string certPassword,
                                     string ssgUsername,
                                     string ssgPassword,
                                     string nativeBaseUri)
        {
            OdataUri       = odataUri;
            ServerAppIdUri = serverAppIdUri;
            NativeBaseUri  = nativeBaseUri;
            WebName        = webname;

            // ensure the webname has a slash.
            // if (!string.IsNullOrEmpty(WebName) && WebName[0] != '/')
            // {
            //     WebName = "/" + WebName;
            // }

            string listDataEndpoint = odataUri + "/_vti_bin/listdata.svc/";

            ApiEndpoint = odataUri + "/_api/";

            if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword))
            {
                // add authentication.
                var authenticationContext = new AuthenticationContext(
                    "https://login.windows.net/" + aadTenantId);

                // Create the Client cert.
                X509Certificate2           cert = new X509Certificate2(certFileName, certPassword);
                ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, cert);

                //ClientCredential clientCredential = new ClientCredential(clientId, clientKey);
                var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientAssertionCertificate);
                task.Wait();
                authenticationResult = task.Result;
                Authorization        = authenticationResult.CreateAuthorizationHeader();
            }
            else
            {
                // authenticate using the SSG.
                string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ssgUsername + ":" + ssgPassword));
                Authorization = "Basic " + credentials;
            }

            // create the HttpClient that is used for our direct REST calls.
            client = new HttpClient();

            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
            client.DefaultRequestHeaders.Add("Authorization", Authorization);
            var digestTask = GetDigest(client);

            digestTask.Wait();
            string digest = digestTask.Result;

            client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
        }
Beispiel #51
0
        public ActionResult ShowThumbnail(string id)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get Group membership
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                // User user = graphConnection.Get<User>(id);
                User user = new User();
                user.ObjectId = id;

                try
                {
                    Stream ms = graphConnection.GetStreamProperty(user, GraphProperty.ThumbnailPhoto, "image/jpeg");
                    user.ThumbnailPhoto = ms;
                }
                catch
                {
                    user.ThumbnailPhoto = null;
                }


                if (user.ThumbnailPhoto != null)
                {
                    return(File(user.ThumbnailPhoto, "image/jpeg"));
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
            }

            return(View());
        }
Beispiel #52
0
        public async Task Run()
        {
            Console.WriteLine($"Starting testing with {userEndIndex - userStartIndex} users.");

            // Try loading from cache
            ScalableTokenCacheHelper.LoadCache();
            IDictionary <int, string> accounts = ScalableTokenCacheHelper.GetAccountIdsByUserNumber();

            foreach (var account in accounts)
            {
                if (account.Key < _userAccountIdentifiers.Length)
                {
                    _userAccountIdentifiers[account.Key] = account.Value;
                }
            }

            // Configuring the http client to trust the self-signed certificate
            var httpClientHandler = new HttpClientHandler();

            httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            var client = new HttpClient(httpClientHandler);

            client.BaseAddress = new Uri(_options.TestServiceBaseUri);

            DateTime startOverall            = DateTime.Now;
            var      finishTime              = DateTime.Now.AddMinutes(_options.RuntimeInMinutes);
            TimeSpan elapsedTime             = TimeSpan.Zero;
            int      requestsCounter         = 0;
            int      authRequestFailureCount = 0;
            int      catchAllFailureCount    = 0;
            int      loop = 0;
            int      tokenReturnedFromCache = 0;

            bool cancelProcessing = false;

            StringBuilder exceptionsDuringRun = new StringBuilder();

            while (!cancelProcessing)
            {
                loop++;
                for (int i = userStartIndex; i <= userEndIndex; i++)
                {
                    bool fromCache = false;
                    try
                    {
                        HttpResponseMessage response;
                        using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, _options.TestUri))
                        {
                            AuthenticationResult authResult = await AcquireTokenAsync(i);

                            if (authResult == null)
                            {
                                authRequestFailureCount++;
                            }
                            else
                            {
                                httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
                                httpRequestMessage.Headers.Add(
                                    "Authorization",
                                    string.Format(
                                        CultureInfo.InvariantCulture,
                                        "{0} {1}",
                                        "Bearer",
                                        authResult?.AccessToken));

                                DateTime start = DateTime.Now;
                                response = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);

                                elapsedTime += DateTime.Now - start;
                                requestsCounter++;
                                if (authResult?.AuthenticationResultMetadata.TokenSource == TokenSource.Cache)
                                {
                                    tokenReturnedFromCache++;
                                    fromCache = true;
                                }
                                else
                                {
                                    if (i % 10 == 0)
                                    {
                                        ScalableTokenCacheHelper.PersistCache();
                                    }
                                }

                                if (!response.IsSuccessStatusCode)
                                {
                                    Console.WriteLine($"Response was not successful. Status code: {response.StatusCode}. {response.ReasonPhrase}");
                                    Console.WriteLine(response.ReasonPhrase);
                                    Console.WriteLine(await response.Content.ReadAsStringAsync());
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        catchAllFailureCount++;
                        Console.WriteLine($"Exception in TestRunner at {i} of {userEndIndex} - {userStartIndex}: {ex.Message}");

                        exceptionsDuringRun.AppendLine($"Exception in TestRunner at {i} of {userEndIndex} - {userStartIndex}: {ex.Message}");
                        exceptionsDuringRun.AppendLine($"{ex}");
                    }

                    Console.Title = $"[{userStartIndex} - {userEndIndex}] #: {i}, Loop: {loop}, " +
                                    $"Time: {(DateTime.Now - startOverall).TotalMinutes:0.00}, " +
                                    $"Req: {requestsCounter}, Cache: {tokenReturnedFromCache}: {fromCache}, " +
                                    $"AuthFail: {authRequestFailureCount}, Fail: {catchAllFailureCount}";

                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo keyInfo = Console.ReadKey();
                        if ((keyInfo.Modifiers == ConsoleModifiers.Control && (keyInfo.Key == ConsoleKey.X || keyInfo.Key == ConsoleKey.C)) || keyInfo.Key == ConsoleKey.Escape)
                        {
                            cancelProcessing = true;
                            break;
                        }
                    }
                }

                UpdateConsoleProgress(startOverall, elapsedTime, requestsCounter, tokenReturnedFromCache, authRequestFailureCount, catchAllFailureCount);

                ScalableTokenCacheHelper.PersistCache();

                if (DateTime.Now >= finishTime)
                {
                    cancelProcessing = true;
                }
            }

            File.AppendAllText(System.Reflection.Assembly.GetExecutingAssembly().Location + ".exceptions.log", exceptionsDuringRun.ToString());
            Console.WriteLine("Test run complete");
        }
        private void WbLoginOnNavigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.ToString().StartsWith("http://localhost/myapp")) {
                var splitted = e.Uri.ToString().Split('&').Select(s => s.Split('=')).ToDictionary(s => s.First(), s => s.Last());
                if (!splitted.ContainsKey("oauth_verifier")) {
                    ((Storyboard)Resources["HidePopupAnimation"]).Begin();
                    return;
                }
                string verifier = splitted["oauth_verifier"];
                var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
                authorizer.GetAccessToken(BaseUrl + "/oauth", requestToken, verifier)
                    .ObserveOnDispatcher()
                    .Subscribe(res => {
                        try {
                            AuthenticationResult result = new AuthenticationResult();
                            result.AuthenticationToken = Uri.UnescapeDataString(res.Token.Key);
                            result.NoteStoreUrl = Uri.UnescapeDataString(res.ExtraData["edam_noteStoreUrl"].First());
                            result.Expiration = long.Parse(res.ExtraData["edam_expires"].First());
                            result.WebApiUrlPrefix = Uri.UnescapeDataString(res.ExtraData["edam_webApiUrlPrefix"].First());
                            result.User = new User();
                            result.User.Id = int.Parse(res.ExtraData["edam_userId"].First());
                            MessageBox.Show("Login Success. Token is " + result.AuthenticationToken);
                        }
                        catch (KeyNotFoundException) {

                        }
                        finally {
                            ((Storyboard)Resources["HidePopupAnimation"]).Begin();
                        }
                    });

                e.Cancel = true;
                wbLogin.Visibility = Visibility.Collapsed;
            }
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.Use(typeof(ConditionalMiddlewareInvoker));

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = AADAppSettings.ClientId,
                Authority = AADAppSettings.Authority,

                // ProtocolValidator = new OpenIdConnectProtocolValidator()
                // {
                //    RequireNonce = false,
                // },

                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // instead of using the default validation (validating against a single issuer value, as we do in line of business apps (single tenant apps)),
                    // we turn off validation
                    //
                    // NOTE:
                    // * In a multitenant scenario you can never validate against a fixed issuer string, as every tenant will send a different one.
                    // * If you don’t care about validating tenants, as is the case for apps giving access to 1st party resources, you just turn off validation.
                    // * If you do care about validating tenants, think of the case in which your app sells access to premium content and you want to limit access only to the tenant that paid a fee,
                    //       you still need to turn off the default validation but you do need to add logic that compares the incoming issuer to a list of tenants that paid you,
                    //       and block access if that’s not the case.
                    // * Refer to the following sample for a custom validation logic: https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet

                    ValidateIssuer = false
                },

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    //If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;

                        ClientCredential credential = new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey);
                        string tenantId             = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signInUserId         = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

                        // Get the access token for AAD Graph. Doing this will also initialize the token cache associated with the authentication context
                        // In theory, you could acquire token for any service your application has access to here so that you can initialize the token cache
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, AADAppSettings.AADGraphResourceId);

                        return(Task.FromResult(0));
                    },

                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        // Save the form in the cookie to prevent it from getting lost in the login redirect
                        FormDataCookie cookie = new FormDataCookie(AADAppSettings.SavedFormDataName);
                        cookie.SaveRequestFormToCookie();

                        return(Task.FromResult(0));
                    }

                    // AuthenticationFailed = (context) =>
                    // {
                    //    // Suppress the exception if you don't want to see the error
                    //   // context.HandleResponse();
                    //    return Task.FromResult(0);
                    // }
                }
            });
        }
Beispiel #55
0
		/// <summary>
		/// Check if authentication succeeded after user is redirected back from the service provider.
		/// </summary>
		/// <param name="context">
		/// The context.
		/// </param>
		/// <returns>
		/// An instance of <see cref="AuthenticationResult"/> containing authentication result. 
		/// </returns>
		public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context) {
			AuthorizedTokenResponse response = this.WebWorker.ProcessUserAuthorization();
			if (response == null) {
				return AuthenticationResult.Failed;
			}

			AuthenticationResult result = this.VerifyAuthenticationCore(response);
            if (result.IsSuccessful && result.ExtraData != null)
            {
                // add the access token to the user data dictionary just in case page developers want to use it
                var wrapExtraData = result.ExtraData.IsReadOnly 
                    ? new Dictionary<string, string>(result.ExtraData) 
                    : result.ExtraData;
                wrapExtraData["accesstoken"] = response.AccessToken;

                AuthenticationResult wrapResult = new AuthenticationResult(
                    result.IsSuccessful,
                    result.Provider,
                    result.ProviderUserId,
                    result.UserName,
                    wrapExtraData
                );

                result = wrapResult;
            }

            return result;
		}
Beispiel #56
0
        private async void AddTodoItem(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (!accounts.Any())
            {
                MessageBox.Show("Please sign in first");
                return;
            }
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            //
            // Get an access token to call the To Do service.
            //
            AuthenticationResult result = null;

            try
            {
                result = await _app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                SetUserName(result.Account);
                UserName.Content = Properties.Resources.UserNotSignedIn;
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                MessageBox.Show("Please re-signIn");
                SignInButton.Content = signInString;
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }

                Dispatcher.Invoke(() =>
                {
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                    MessageBox.Show("Unexpected error: " + message);
                });

                return;
            }

            //
            // Call the To Do service.
            //

            // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode Todo item, to POST to the todo list web api.
            HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", TodoText.Text) });

            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                GetTodoList();
            }
            else
            {
                MessageBox.Show("An error occurred : " + response.ReasonPhrase);
            }
        }
 public AdalAccessToken(AuthenticationResult authResult, AdalTokenProvider tokenProvider, AdalConfiguration configuration)
 {
     AuthResult = authResult;
     this.tokenProvider = tokenProvider;
     Configuration = configuration;
 }
Beispiel #58
0
        private async void GetTodoList(bool isAppStarting)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (!accounts.Any())
            {
                SignInButton.Content = signInString;
                return;
            }

            //
            // Get an access token to call the ToDo service.
            //
            AuthenticationResult result = null;

            try
            {
                result = await _app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                Dispatcher.Invoke(
                    () =>
                {
                    SignInButton.Content = clearCacheString;
                    SetUserName(result.Account);
                });
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                if (!isAppStarting)
                {
                    MessageBox.Show("Please sign in to view your To-Do list");
                    SignInButton.Content = signInString;
                }
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }
                MessageBox.Show(message);

                UserName.Content = Properties.Resources.UserNotSignedIn;
                return;
            }

            // Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do list service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "/api/todolist");

            if (response.IsSuccessStatusCode)
            {
                // Read the response and databind to the GridView to display To Do items.
                string s = await response.Content.ReadAsStringAsync();

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                List <TodoItem>      toDoArray  = serializer.Deserialize <List <TodoItem> >(s);

                Dispatcher.Invoke(() =>
                {
                    TodoList.ItemsSource = toDoArray.Select(t => new { t.Title });
                });
            }
            else
            {
                MessageBox.Show("An error occurred : " + response.ReasonPhrase);
            }

            return;
        }
Beispiel #59
0
        public ActionResult Edit([Bind(Include = "ObjectId,UserPrincipalName,DisplayName,AccountEnabled,GivenName,Surname,JobTitle,Department,Mobile,StreetAddress,City,State,Country,")] User user, FormCollection values)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and update single User
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                graphConnection.Update(user);

                // update thumbnail photo
                if (!String.IsNullOrEmpty(values["photofile"]))
                {
                    //string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
                    //string filename = Path.GetFileName(values["photofile"]);
                    //Image image = Image.FromFile(filename);

                    var   imageFile = Path.Combine(Server.MapPath("~/app_data"), values["photofile"]);
                    Image image     = Image.FromFile(imageFile);

                    MemoryStream stream = new MemoryStream();
                    image.Save(stream, ImageFormat.Jpeg);

                    // Write the photo file to the Graph service.
                    graphConnection.SetStreamProperty(user, GraphProperty.ThumbnailPhoto, stream, "image/jpeg");
                }


                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Beispiel #60
0
        public async System.Threading.Tasks.Task GetSecrets() {
            _clientId = GetAppSetting("clientId");
            _clientSecret = GetAppSetting("clientSecret");
            _tenantId = GetAppSetting("tenantId");
            _subId = GetAppSetting("subId");

            _credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(_clientId,
                                                                                   _clientSecret,
                                                                                   _tenantId,
                                                                                   AzureEnvironment.AzureGlobalCloud);

            KeyVaultClient kvClient = new KeyVaultClient(
                async (string authority, string resource, string scope) =>
                {
                    AuthenticationContext authContext = new AuthenticationContext(authority);
                    ClientCredential clientCred = new ClientCredential(_clientId, _clientSecret);
                    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
                    if (result == null)
                    {
                        throw new InvalidOperationException("Failed to retrieve access token for Key Vault");
                    }

                    return result.AccessToken;
                });
            _gitToken = (await kvClient.GetSecretAsync("https://appsvcbuild-vault.vault.azure.net/", "gitToken")).Value;
            _sendGridApiKey = (await kvClient.GetSecretAsync("https://appsvcbuild-vault.vault.azure.net/", "sendGridApiKey")).Value;
            _appsvcbuildfuncMaster = (await kvClient.GetSecretAsync("https://appsvcbuild-vault.vault.azure.net/", "appsvcbuildfuncMaster")).Value;
            _acrPassword = (await kvClient.GetSecretAsync("https://appsvcbuild-vault.vault.azure.net/", "acrPassword")).Value;
            _pipelineToken = (await kvClient.GetSecretAsync("https://appsvcbuild-vault.vault.azure.net/", "pipelineToken")).Value;

            if (_clientId == "")
            {
                throw new Exception("missing appsetting clientId ");
            }
            if (_clientSecret == "")
            {
                throw new Exception("missing appsetting clientSecret ");
            }
            if (_tenantId == "")
            {
                throw new Exception("missing appsetting tenantId ");
            }
            if (_subId == "")
            {
                throw new Exception("missing appsetting subId ");
            }
            if (_gitToken == "")
            {
                throw new Exception("missing setting gitToken in keyvault");
            }
            if (_sendGridApiKey == "")
            {
                throw new Exception("missing setting gitToken in sendGridApiKey");
            }
            if (_appsvcbuildfuncMaster == "")
            {
                throw new Exception("missing setting gitToken in appsvcbuildfuncMaster");
            }
            if (_acrPassword == "")
            {
                throw new Exception("missing setting gitToken in appsvcbuildfuncMaster");
            }
            if (_pipelineToken == "")
            {
                throw new Exception("missing setting gitToken in appsvcbuildfuncMaster");
            }
            return;
        }