private async System.Threading.Tasks.Task AcquireAccessTokenAsync(string ClientId)
        {
            Cursor  = Cursors.WaitCursor;
            Enabled = false;

            string[] scopes = Util.MailboxViewerScopes();

            _pca = PublicClientApplicationBuilder.Create(ClientId).Build();

            StringBuilder stringBuilder = new StringBuilder();

            try
            {
                stringBuilder.AppendLine("MSAL - AcquireTokenAsync");
                stringBuilder.AppendLine("Application ID : " + ClientId);
                stringBuilder.AppendLine("Scope : " + string.Join(",", scopes));

                _ar = await _pca.AcquireTokenInteractive(scopes).WithPrompt(Prompt.ForceLogin).ExecuteAsync();

                stringBuilder.AppendLine("Result : Success");
                stringBuilder.AppendLine("AccessToken : " + (_ar.AccessToken ?? ""));
                stringBuilder.AppendLine("ExpiresOn : " + _ar.ExpiresOn.ToString());
                stringBuilder.AppendLine("IdToken : " + (_ar.IdToken ?? ""));
                stringBuilder.AppendLine("Scope : " + string.Join(",", _ar.Scopes));
                stringBuilder.AppendLine("UniqueId : " + (_ar.UniqueId ?? ""));
                stringBuilder.AppendLine("Username : "******""));
                stringBuilder.AppendLine("Identifier : " + (_ar.Account.HomeAccountId.Identifier ?? ""));
                stringBuilder.AppendLine("Name : " + (_ar.Account.Username ?? ""));

                Properties.Settings.Default.Save();
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                stringBuilder.AppendLine("Result : Fail");
                stringBuilder.AppendLine("Message : " + ex.Message);

                if (ex.Message != "User canceled authentication")
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor");
                }
            }
            finally
            {
                Cursor  = Cursors.Default;
                Enabled = true;
            }

            Util.WriteSystemLog("AcquireViewerTokenForm", stringBuilder.ToString());
        }
Exemple #2
0
        public Connector()
        {
            // Create Client Application and Authentication Provider
            _clientApp = InteractiveAuthenticationProvider.CreateClientApplication(
                _clientId,
                FileBasedTokenStorageProvider.Instance);

            _clientApp.RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";

            var authProvider = new InteractiveAuthenticationProvider(_clientApp, _scopes);

            // Create GraphServiceClient with middleware pipeline setup
            _graph = new GraphServiceClient(authProvider);
        }
Exemple #3
0
        private static async Task <AuthenticationResult> Login()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            AuthenticationResult authResult = null;

            string[] scopes = new string[] { "user.read", "Directory.Read.All", "Directory.ReadWrite.All" };
            try
            {
                var _clientId = config.ClientId;   // this is an app client that allows 'client app' authentication
                var _instance = config.Instance.Replace("{0}", "");
                var _tenant   = config.Tenant;

                _clientApp = PublicClientApplicationBuilder.Create(_clientId)
                             .WithAuthority($"{_instance}{_tenant}")
                             //.WithAuthority(new Uri(config.Authority))
                             .WithDefaultRedirectUri()
                             //.WithRedirectUri("msal2676c812-ca98-4688-ad5c-9dcb92096171://auth")
                             .Build();
                authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
                             .ExecuteAsync();
            }
            //catch (MsalUiRequiredException ex)
            //{
            //    // A MsalUiRequiredException happened on AcquireTokenSilent.
            //    // This indicates you need to call AcquireTokenInteractive to acquire a token
            //    System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            //    try
            //    {
            //        authResult = await Program.PublicClientApp.AcquireTokenInteractive(scopes)
            //            //.WithAccount(accounts.FirstOrDefault())
            //            //.WithPrompt(Prompt.SelectAccount)
            //            .ExecuteAsync();
            //    }
            //    catch (MsalException msalex)
            //    {
            //        Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
            //    }
            //}
            catch (MsalException msalex)
            {
                Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{ex}");
            }
            return(authResult);
        }
Exemple #4
0
        private async Task CreateSSHCertTestAsync(LabResponse labResponse)
        {
            IPublicClientApplication pca = PublicClientApplicationBuilder
                                           .Create(labResponse.App.AppId)
                                           .WithRedirectUri(SeleniumWebUI.FindFreeLocalhostRedirectUri())
                                           .WithTestLogging()
                                           .Build();

            TokenCacheAccessRecorder userCacheAccess = pca.UserTokenCache.RecordAccess();

            Trace.WriteLine("Part 1 - Acquire an SSH cert interactively ");
            string jwk = CreateJwk();

            AuthenticationResult result = await pca
                                          .AcquireTokenInteractive(s_scopes)
                                          .WithCustomWebUi(CreateSeleniumCustomWebUI(labResponse.User, Prompt.ForceLogin))
                                          .WithSSHCertificateAuthenticationScheme(jwk, "key1")
                                          .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                                          .ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(0, 1);
            Assert.AreEqual("ssh-cert", result.TokenType);
            IAccount account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(1, 1); // the assert calls GetAccounts

            Trace.WriteLine("Part 2 - Acquire a token silent with the same keyID - should be served from the cache");
            result = await pca
                     .AcquireTokenSilent(s_scopes, account)
                     .WithSSHCertificateAuthenticationScheme(jwk, "key1")
                     .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                     .ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(2, 1);

            account = await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);

            userCacheAccess.AssertAccessCounts(3, 1);

            Trace.WriteLine("Part 3 - Acquire a token silent with a different keyID - should not sbe served from the cache");
            result = await pca
                     .AcquireTokenSilent(s_scopes, account)
                     .WithSSHCertificateAuthenticationScheme(jwk, "key2")
                     .ExecuteAsync(new CancellationTokenSource(_interactiveAuthTimeout).Token)
                     .ConfigureAwait(false);

            Assert.AreEqual("ssh-cert", result.TokenType);
            userCacheAccess.AssertAccessCounts(4, 2);
            await MsalAssert.AssertSingleAccountAsync(labResponse, pca, result).ConfigureAwait(false);
        }
Exemple #5
0
        private static async Task OAuthSSO()
        {
            string[] scopes = new string[] { "user.read" };

            app = PublicClientApplicationBuilder.Create(configuration["Azure:ClientID"])
                  //.WithRedirectUri(configuration["Azure:Redirect"])
                  .WithAuthority(AzureCloudInstance.AzurePublic, configuration["Azure:TenantID"])
                  .Build();


            var accounts = await app.GetAccountsAsync();

            AuthenticationResult result = null;

            if (accounts.Any())
            {
                result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                         .ExecuteAsync();
            }
            else
            {
                try
                {
                    result = await app.AcquireTokenByIntegratedWindowsAuth(scopes)
                             .ExecuteAsync(CancellationToken.None);
                }
                catch (MsalUiRequiredException ex)
                {
                    Console.WriteLine(string.Concat("AAD error: ", ex.Message, " Code: ", ex.ErrorCode));
                }
                catch (MsalServiceException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (MsalClientException ex)
                {
                    Console.WriteLine(ex.ErrorCode);

                    // ErrorCode kann hier nachgeschlagen werden : https://docs.microsoft.com/en-us/dotnet/api/microsoft.identity.client.msalerror?view=azure-dotnet

                    Console.WriteLine(ex.Message);

                    if (ex.InnerException != null && ex.InnerException is MsalServiceException)
                    {
                        Console.WriteLine(((MsalServiceException)ex.InnerException).Message);
                        Console.WriteLine(((MsalServiceException)ex.InnerException).ResponseBody);
                    }
                }
            }
        }
        internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext)
        {
            if (authContext is null)
            {
                throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
            }

            IAuthenticationProvider authProvider = null;

            switch (authContext.AuthType)
            {
            case AuthenticationType.Delegated:
            {
                IPublicClientApplication publicClientApp = PublicClientApplicationBuilder
                                                           .Create(authContext.ClientId)
                                                           .WithTenantId(authContext.TenantId)
                                                           .Build();

                ConfigureTokenCache(publicClientApp.UserTokenCache, authContext);
                authProvider = new DeviceCodeProvider(publicClientApp, authContext.Scopes, async(result) => {
                        await Console.Out.WriteLineAsync(result.Message);
                    });
                break;
            }

            case AuthenticationType.AppOnly:
            {
                IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder
                                                                       .Create(authContext.ClientId)
                                                                       .WithTenantId(authContext.TenantId)
                                                                       .WithCertificate(string.IsNullOrEmpty(authContext.CertificateThumbprint) ? GetCertificateByName(authContext.CertificateName) : GetCertificateByThumbprint(authContext.CertificateThumbprint))
                                                                       .Build();

                ConfigureTokenCache(confidentialClientApp.AppTokenCache, authContext);
                authProvider = new ClientCredentialProvider(confidentialClientApp);
                break;
            }

            case AuthenticationType.UserProvidedAccessToken:
            {
                authProvider = new DelegateAuthenticationProvider((requestMessage) => {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer",
                                                                                             new NetworkCredential(string.Empty, GraphSession.Instance.UserProvidedToken).Password);
                        return(Task.CompletedTask);
                    });
                break;
            }
            }
            return(authProvider);
        }
Exemple #7
0
        public void Initialize()
        {
            if (clientApp == null)
            {
                IsAuthenticated = false;

                clientApp = PublicClientApplicationBuilder.Create(param.AzureADClientId)
                            .WithAuthority(param.AuthorityAudience)
                            .WithRedirectUri(param.PublicClientRedirectUri)
                            .WithIosKeychainSecurityGroup(param.IosKeychainSecurityGroups)
                            .WithParentActivityOrWindow(() => MainActivity?.Invoke() ?? UIParent?.Invoke())
                            .Build();
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            app = PublicClientApplicationBuilder.Create(ClientId)
                  .WithAuthority(Authority)
                  .WithDefaultRedirectUri()
                  .Build();

            httpClient = new HttpClient(new HttpClientHandler
            {
                AllowAutoRedirect = false
            });
        }
        private static async Task FetchTokenAndCallGraphAsync(IPublicClientApplication pca, Task <AuthenticationResult> authTask)
        {
            await authTask.ConfigureAwait(false);

            Console.BackgroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("Token is {0}", authTask.Result.AccessToken);
            Console.ResetColor();


            Console.BackgroundColor = ConsoleColor.DarkMagenta;
            await DisplayAccountsAsync(pca).ConfigureAwait(false);

            Console.ResetColor();
        }
Exemple #10
0
        public MainPage()
        {
            this.InitializeComponent();

            _app = PublicClientApplicationBuilder
                   .Create(CLIENT_ID)
                   .WithTenantId(TENANT_ID)
                   .WithRedirectUri(REDIRECT_URI)
                   .WithUnoHelpers()
#if __IOS__
                   .WithIosKeychainSecurityGroup("86AC3CZ5DN.com.microsoft.adalcache")
#endif
                   .Build();
        }
Exemple #11
0
        //gavdcodeend 01

        //gavdcodebegin 02
        static GraphServiceClient GetGraphClientDel(string TenantId, string ClientId)
        {
            IPublicClientApplication clientApplication = PublicClientApplicationBuilder
                                                         .Create(ClientId)
                                                         .WithTenantId(TenantId)
                                                         //.WithRedirectUri("http://localhost") // Only if redirect in the App Reg.
                                                         .Build();

            UsernamePasswordProvider authenticationProvider =
                new UsernamePasswordProvider(clientApplication);
            GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);

            return(graphClient);
        }
        public DeviceFlowAzureCredential(IOptions <AzureConfiguration> configuration, IEnumerable <string> scopes)
        {
            var configuration1 = configuration?.Value ?? throw new ArgumentNullException(nameof(configuration));

            _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes));

            // Create the public client application (desktop app), with a default redirect URI
            // for these. Enable PoP
            _application = PublicClientApplicationBuilder.Create(configuration1.AppId)
                           .WithAuthority(AzureCloudInstance.AzurePublic, configuration1.Tenant)
                           .WithRedirectUri($"msal{configuration1.AppId}://auth")
                           .WithExperimentalFeatures() // Needed for PoP
                           .Build();
        }
Exemple #13
0
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

        /// <summary>
        /// Log the user in to either Office 365 or OneDrive consumer
        /// </summary>
        /// <returns>A task to await on</returns>
        public async Task <bool> SignInUser(object parentWindow = null)
        {
            logger.LogInformation("Sign in");
            var result = false;

            // Instantiate the app with AAD
            AADAppContext = PublicClientApplicationBuilder.Create(AADClientId)
                            .WithRedirectUri("http://localhost:7111")
                            .Build();

            string status;

            try
            {
                try
                {
                    var accounts = await AADAppContext.GetAccountsAsync();

                    UserCredentials = await AADAppContext.AcquireTokenSilent(AADScopes, accounts.FirstOrDefault())
                                      .ExecuteAsync();
                }
                catch (MsalUiRequiredException)
                {
                    UserCredentials = await AADAppContext.AcquireTokenInteractive(AADScopes)
                                      .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                                      .ExecuteAsync();
                }
                if (UserCredentials != null)
                {
                    status = "Signed in as " + UserCredentials.Account.Username;
                    logger.LogInformation($"{status}");
                    InitializeGraph();
                    result = true;
                }
            }

            catch (MsalServiceException serviceEx)
            {
                status = $"Could not sign in, error code: " + serviceEx.ErrorCode;
                logger.LogError($"{status}, {serviceEx.Message}");
            }

            catch (Exception ex)
            {
                status = $"Error Acquiring Token: {ex}";
                logger.LogError($"{status}, {ex.Message}");
            }

            return(result);
        }
Exemple #14
0
        public WebStorageService(IIdentityService identityService = null)
        {
            this.identityService = identityService;
            string appId = null;

            GetApplicationId(ref appId);
            if (appId != null)
            {
                var builder = PublicClientApplicationBuilder.Create(appId);
                builder.WithRedirectUri("wafe5b8cee6-8ba0-46c5-96ef-a3c8a1e2bb26://auth");
                identityService?.Build(builder);
                publicClient = builder.Build();
            }
        }
 /// <summary>
 /// Constructs a new <see cref="DeviceCodeProvider"/>
 /// </summary>
 /// <param name="publicClientApplication">A <see cref="IPublicClientApplication"/> to pass to <see cref="DeviceCodeProvider"/> for authentication.</param>
 /// <param name="scopes">Scopes required to access Microsoft graph.</param>
 /// <param name="deviceCodeResultCallback">Callback containing information to show the user about how to authenticate and enter the device code.</param>
 public DeviceCodeProvider(
     IPublicClientApplication publicClientApplication,
     string[] scopes,
     Func <DeviceCodeResult, Task> deviceCodeResultCallback = null)
     : base(scopes)
 {
     ClientApplication = publicClientApplication ?? throw new AuthenticationException(
                                   new Error
     {
         Code    = ErrorConstants.Codes.InvalidRequest,
         Message = string.Format(ErrorConstants.Message.NullValue, "publicClientApplication")
     });
     DeviceCodeResultCallback = deviceCodeResultCallback ?? DefaultDeviceCallback;
 }
        /// <summary>
        /// Tworzy klasę autentykacji z domyślnym Managerem Poświadczeń (Microsoft)
        /// </summary>
        public MicrosoftAuthentication()
        {
            mClientId         = mConfigurationReader.Setting <string>("MicrosoftClientId");
            mTokencacheHelper = new TokenCacheHelper();

            this.mCredentialsManager = new CredentialsManager(AuthenticationProvider.Microsoft);
            mClientApp = PublicClientApplicationBuilder.Create(mClientId)
                         .WithAuthority($"{mInstance}{mTenant}")
                         .WithDefaultRedirectUri()
                         .Build();

            // Odpowiada za szybkie logowanie za pomoca cache tokena
            mTokencacheHelper.EnableSerialization(mClientApp.UserTokenCache);
        }
Exemple #17
0
        static string[] clientCapabilities = { "ProtApp" };                       // It is must to have these capabilities

        // private constructor for singleton
        private PCAWrapper()
        {
            // Create PCA once. Make sure that all the config parameters below are passed
            // ClientCapabilities - must have ProtApp
            var builder = PublicClientApplicationBuilder
                          .Create(_clientID)
                          .WithAuthority(_authority)
                          .WithBroker()
                          .WithClientCapabilities(clientCapabilities)
                          .WithTenantId(_tenantID)
                          .WithRedirectUri(_redirectURI);

            PCA = builder.Build();
        }
Exemple #18
0
        public async Task NullAccount_EmptyLoginHintAsync()
        {
            IPublicClientApplication app = PublicClientApplicationBuilder
                                           .Create(MsalTestConstants.ClientId)
                                           .Build();

            await AssertException.TaskThrowsAsync <ArgumentNullException>(
                () => app.AcquireTokenSilent(MsalTestConstants.Scope.ToArray(), (string)null).ExecuteAsync()).ConfigureAwait(false);

            var ex = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(
                () => app.AcquireTokenSilent(MsalTestConstants.Scope.ToArray(), (IAccount)null).ExecuteAsync()).ConfigureAwait(false);

            Assert.AreEqual(MsalError.UserNullError, ex.ErrorCode);
        }
Exemple #19
0
        public GraphAuthProvider(string clientId, string tenantId, string[] scopes)
        {
            _scopes = scopes;

            var authority = "https://login.microsoftonline.com/" + tenantId;

            _app = PublicClientApplicationBuilder
                   .Create(clientId)
                   .WithAuthority(authority)
                   .WithDefaultRedirectUri()
                   .Build();

            TokenCacheHelper.EnableSerialization(_app.UserTokenCache);
        }
        /// <summary>
        /// Tries to acquire an application Microsoft Graph Access Token for the provided scopes interactively by allowing the user to log in
        /// </summary>
        /// <param name="clientId">ClientId to use to acquire the token. Required.</param>
        /// <param name="scopes">Array with scopes that should be requested access to. Required.</param>
        /// <returns><see cref="GraphToken"/> instance with the token</returns>
        public static GenericToken AcquireApplicationTokenInteractive(string clientId, string[] scopes, AzureEnvironment azureEnvironment)
        {
            var endPoint = GetAzureADLoginEndPoint(azureEnvironment);

            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (scopes == null || scopes.Length == 0)
            {
                throw new ArgumentNullException(nameof(scopes));
            }


            if (publicClientApplication == null)
            {
                publicClientApplication = PublicClientApplicationBuilder.Create(clientId).WithRedirectUri($"{endPoint}/common/oauth2/nativeclient").Build();
            }

            AuthenticationResult tokenResult = null;

            var account = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult();

            try
            {
                tokenResult = publicClientApplication.AcquireTokenSilent(scopes, account.First()).ExecuteAsync().GetAwaiter().GetResult();
            }
            catch
            {
                try
                {
                    tokenResult = publicClientApplication.AcquireTokenInteractive(scopes).WithExtraScopesToConsent(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync().GetAwaiter().GetResult();
                }
                catch (MsalUiRequiredException msalEx)
                {
                    if (msalEx.Classification == UiRequiredExceptionClassification.ConsentRequired)
                    {
                        if (clientId == PnPConnection.PnPManagementShellClientId)
                        {
                            throw new PSInvalidOperationException("Please provide consent to the PnP Management Shell application with 'Register-PnPManagementShellAccess'");
                        }
                        else
                        {
                            throw msalEx;
                        }
                    }
                }
            }
            return(new GenericToken(tokenResult.AccessToken));
        }
Exemple #21
0
        public MsalLoginAndGraph()
        {
            this.InitializeComponent();

            _app = PublicClientApplicationBuilder
                   .Create(CLIENT_ID)
                   .WithTenantId(TENANT_ID)
                   .WithRedirectUri(REDIRECT_URI)
                   .WithUnoHelpers()
#if __IOS__
                   .WithIosKeychainSecurityGroup("com.companyname.SamplesApp")
#endif
                   .Build();
        }
Exemple #22
0
        /// <summary>
        /// Creates a new SharedTokenCacheCredential with the specifeid options, which will authenticate users with the specified application.
        /// </summary>
        /// <param name="clientId">The client id of the application to which the users will authenticate</param>
        /// <param name="username">The username of the user to authenticate</param>
        /// TODO: need to link to info on how the application has to be created to authenticate users, for multiple applications
        /// <param name="options">The client options for the newly created SharedTokenCacheCredential</param>
        public SharedTokenCacheCredential(string clientId, string username, SharedTokenCacheCredentialOptions options)
        {
            _clientId = clientId ?? throw new ArgumentNullException(nameof(clientId));

            options ??= new SharedTokenCacheCredentialOptions();

            _username = username;

            HttpPipeline pipeline = HttpPipelineBuilder.Build(options);

            _pubApp = PublicClientApplicationBuilder.Create(_clientId).WithHttpClientFactory(new HttpPipelineClientFactory(pipeline)).Build();

            _cacheReader = new MsalCacheReader(_pubApp.UserTokenCache, options.CacheFilePath, options.CacheAccessRetryCount, options.CacheAccessRetryDelay);
        }
Exemple #23
0
        /// <summary>
        /// Apply this authenticator to the given authentication parameters.
        /// </summary>
        /// <param name="parameters">The complex object containing authentication specific information.</param>
        /// <param name="promptAction">The action used to prompt for interaction.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult" /> that represents the access token generated as result of a successful authenication.
        /// </returns>
        public override async Task <AuthenticationResult> AuthenticateAsync(AuthenticationParameters parameters, Action <string> promptAction = null, CancellationToken cancellationToken = default)
        {
            IPublicClientApplication app = GetClient(parameters.Account, parameters.Environment).AsPublicClient();

            IEnumerable <IAccount> accounts = await app.GetAccountsAsync().ConfigureAwait(false);

            AuthenticationResult authResult = await app.AcquireTokenSilent(
                parameters.Scopes,
                accounts.FirstOrDefault(a => a.HomeAccountId.ObjectId.Equals(((SilentParameters)parameters).UserId)))
                                              .ExecuteAsync(cancellationToken)
                                              .ConfigureAwait(false);

            return(authResult);
        }
        public Connector()
        {
            // Create Client Application and Authentication Provider
            _clientApp = InteractiveAuthenticationProvider.CreateClientApplication(
                _clientId,
                new FileBasedTokenStorageProvider());

            _clientApp.RedirectUri = "urn:ietf:wg:oauth:2.0:oob:myappname";

            var authProvider = new InteractiveAuthenticationProvider(_clientApp, _scopes);

            // Create GraphServiceClient with middleware pipeline setup
            _graph = new GraphServiceClient(authProvider);
        }
Exemple #25
0
        public void CreatePublicClient(string authority = null)
        {
            PublicClientApp = PublicClientApplicationBuilder
                              .Create(ClientId)
                              .WithAuthority(authority ?? "https://login.microsoftonline.com/organizations")
                              .WithRedirectUri("http://localhost:8400")
                              .WithLogging((level, message, pii) =>
            {
                Console.WriteLine(string.Format("[MSAL] {0}: {1}", level, message));
            })
                              .Build();

            RegisterCache(PublicClientApp);
        }
        /// <summary>
        /// Creates an instance of the UsernamePasswordCredential with the details needed to authenticate against Azure Active Directory with a simple username
        /// and password.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password">The user account's user name, UPN.</param>
        /// <param name="clientId">The client (application) ID of an App Registration in the tenant.</param>
        /// <param name="tenantId">The Azure Active Directory tenant (directory) ID or name.</param>
        /// <param name="options">The client options for the newly created UsernamePasswordCredential</param>
        public UsernamePasswordCredential(string username, string password, string clientId, string tenantId, AzureCredentialOptions options)
        {
            _username = username ?? throw new ArgumentNullException(nameof(username));

            _password = (password != null) ? password.ToSecureString() : throw new ArgumentNullException(nameof(password));

            _options = options ?? new AzureCredentialOptions();

            _pipeline = HttpPipelineBuilder.Build(_options);

            _clientDiagnostics = new ClientDiagnostics(options);

            _pubApp = PublicClientApplicationBuilder.Create(clientId).WithHttpClientFactory(new HttpPipelineClientFactory(_pipeline)).WithTenantId(tenantId).Build();
        }
Exemple #27
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            Debug.WriteLine("Sync Backup started.");
            ExecutingPlatform.Current = AppPlatform.UWP;

            var settingsFacade = new SettingsFacade(new SettingsAdapter());

            if (!settingsFacade.IsBackupAutouploadEnabled || !settingsFacade.IsLoggedInToBackupService)
            {
                return;
            }

            try
            {
                IPublicClientApplication pca = PublicClientApplicationBuilder
                                               .Create(ServiceConstants.MSAL_APPLICATION_ID)
                                               .WithRedirectUri($"msal{ServiceConstants.MSAL_APPLICATION_ID}://auth")
                                               .Build();

                var backupManager = new BackupManager(
                    new OneDriveService(pca),
                    new WindowsFileStore(),
                    new ConnectivityAdapter());

                var backupService = new BackupService(backupManager, settingsFacade);

                DateTime backupDate = await backupService.GetBackupDateAsync();

                if (settingsFacade.LastDatabaseUpdate > backupDate)
                {
                    return;
                }

                await backupService.RestoreBackupAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Debug.WriteLine("Sync Backup failed.");
            }
            finally
            {
                settingsFacade.LastExecutionTimeStampSyncBackup = DateTime.Now;
                Debug.WriteLine("Sync Backup finished.");
                deferral.Complete();
            }
        }
Exemple #28
0
        private async Task <AuthenticationResult> RunAtsAsync(IPublicClientApplication pca)
        {
            string reqAuthority = pca.Authority;


            string loginHint = GetLoginHint();

            if (!string.IsNullOrEmpty(loginHint) && cbxAccount.SelectedIndex > 0)
            {
                throw new InvalidOperationException("[TEST APP FAILURE] Please use either the login hint or the account");
            }

            if (!string.IsNullOrEmpty(loginHint))
            {
                if (IsMsaPassthroughConfigured())
                {
                    throw new InvalidAsynchronousStateException(
                              "[TEST APP FAILURE] Do not use login hint on AcquireTokenSilent for MSA-Passthrough. Use the IAccount overload.");
                }

                Log($"ATS with login hint: " + loginHint);
                return(await pca.AcquireTokenSilent(GetScopes(), loginHint)
                       .ExecuteAsync()
                       .ConfigureAwait(false));
            }

            if (cbxAccount.SelectedItem != null &&
                cbxAccount.SelectedItem != s_nullAccount)
            {
                var acc = (cbxAccount.SelectedItem as AccountModel).Account;

                // Today, apps using MSA-PT must manually target the correct tenant
                if (IsMsaPassthroughConfigured() && acc.HomeAccountId.TenantId == "9188040d-6c67-4c5b-b112-36a304b66dad")
                {
                    reqAuthority = "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a";
                }

                Log($"ATS with IAccount for {acc?.Username ?? acc.HomeAccountId.ToString() ?? "null"}");
                return(await pca.AcquireTokenSilent(GetScopes(), acc)
                       .WithAuthority(reqAuthority)
                       .ExecuteAsync()
                       .ConfigureAwait(false));
            }

            Log($"ATS with no account or login hint ... will fail with UiRequiredEx");
            return(await pca.AcquireTokenSilent(GetScopes(), (IAccount)null)
                   .ExecuteAsync()
                   .ConfigureAwait(false));
        }
    /// <summary>
    /// Implements token acquisition logic via the Microsoft Authentication Library.
    ///
    /// /// </summary>
    /// <param name="identity"></param>
    /// <param name="authority"></param>
    /// <param name="resource"></param>
    /// <param name="claims"></param>
    /// <returns></returns>
    public async Task <AuthenticationResult> AcquireTokenAsync(string authority, string resource, string claims, bool isMultiTenantApp = true)
    {
        AuthenticationResult result = null;

        // Create an auth context using the provided authority and token cache
        if (isMultitenantApp)
        {
            _app = PublicClientApplicationBuilder.Create(appInfo.ApplicationId)
                   .WithAuthority(authority)
                   .WithDefaultRedirectUri()
                   .Build();
        }
        else
        {
            if (authority.ToLower().Contains("common"))
            {
                var authorityUri = new Uri(authority);
                authority = String.Format("https://{0}/{1}", authorityUri.Host, tenant);
            }
            _app = PublicClientApplicationBuilder.Create(appInfo.ApplicationId)
                   .WithAuthority(authority)
                   .WithDefaultRedirectUri()
                   .Build();
        }
        var accounts = (_app.GetAccountsAsync()).GetAwaiter().GetResult();

        // Append .default to the resource passed in to AcquireToken().
        string[] scopes = new string[] { resource[resource.Length - 1].Equals('/') ? $"{resource}.default" : $"{resource}/.default" };

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

        catch (MsalUiRequiredException)
        {
            result = _app.AcquireTokenInteractive(scopes)
                     .WithAccount(accounts.FirstOrDefault())
                     .WithPrompt(Prompt.SelectAccount)
                     .ExecuteAsync()
                     .ConfigureAwait(false)
                     .GetAwaiter()
                     .GetResult();
        }

        // Return the token. The token is sent to the resource.
        return(result);
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="MsalProvider"/> class.
        /// </summary>
        /// <param name="client">Existing <see cref="IPublicClientApplication"/> instance.</param>
        /// <param name="provider">Existing <see cref="IAuthenticationProvider"/> instance.</param>
        /// <returns>A <see cref="Task"/> returning a <see cref="MsalProvider"/> instance.</returns>
        public static async Task <MsalProvider> CreateAsync(IPublicClientApplication client, IAuthenticationProvider provider)
        {
            //// TODO: Check all config provided

            var msal = new MsalProvider
            {
                Client   = client,
                Provider = provider,
                Graph    = new GraphServiceClient(provider)
            };

            await msal.TrySilentSignInAsync();

            return(msal);
        }