public static async Task SendRequest(string passwordid, Microsoft.Extensions.Logging.LogLevel?logLevel)
        {
            var level = LoggerConfiguration.ReadFromJsonFile("appsettings.json");

            if (logLevel.HasValue)
            {
                level = logLevel.GetValueOrDefault();
            }

            ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
                                                                builder
                                                                .AddFilter("Password.Vault.Cli.Passwords", level)
                                                                .AddConsole()
                                                                .AddSimpleConsole(options =>
            {
                options.SingleLine      = true;
                options.TimestampFormat = "hh:mm:ss ";
            })

                                                                );

            PasswordConfiguration config = PasswordConfiguration.ReadFromJsonFile("appsettings.json");

            var appConfig = config.PublicClientApplicationOptions;
            var app       = PublicClientApplicationBuilder.CreateWithApplicationOptions(appConfig)
                            .WithDefaultRedirectUri()
                            .Build();

            ILogger <Passwords> logger = loggerFactory.CreateLogger <Passwords>();
            Passwords           p      = new Passwords(app, config, logger);
            await p.GetPasswordHistory(passwordid);
        }
Пример #2
0
        private static async Task <string> GetUserNameByCredentialProvider()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            PublicClientApplicationOptions options = new PublicClientApplicationOptions
            {
                ClientId = config.PublicClientId
            };


            var application = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                              .WithRedirectUri(config.RedirectUri)
                              .WithAuthority(AzureCloudInstance.AzurePublic, config.Tenant)
                              .Build();

            UsernamePasswordProvider authProvider = new UsernamePasswordProvider(application, ApplicaionScopes);
            await application.AcquireTokenByUsernamePassword(ApplicaionScopes, LogonName, Passcode).
            ExecuteAsync();

            await authProvider.ClientApplication.AcquireTokenByUsernamePassword(ApplicaionScopes, LogonName, Passcode).
            ExecuteAsync();

            PublicGraphClient = new GraphServiceClient(authProvider);


            User me = await PublicGraphClient.Me.Request().GetAsync();

            Console.WriteLine($"Logged in as [{me.DisplayName}] @ {DateTime.Now.ToString()}.");
            Console.WriteLine();
            return(me.Id);
        }
Пример #3
0
        public async Task <string> AcquireTokenByUsernamePasswordAsync()
        {
            var options = new PublicClientApplicationOptions()
            {
                ClientId           = azureSetting.ClientId,
                TenantId           = azureSetting.TenantId,
                AzureCloudInstance = AzureCloudInstance.AzurePublic,
            };

            var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).Build();

            string[] scopes = { azureSetting.GraphResource };

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

            if (accounts.Any())
            {
                var result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();

                return(result.AccessToken);
            }
            else
            {
                var result = await app.AcquireTokenByUsernamePassword(scopes, azureSetting.Username, azureSetting.PasswordSecure).ExecuteAsync();

                return(result.AccessToken);
            }
        }
        public AzureADv2TokenCache(IAppSettings aadConfig, ITraceLogger iLogger, bool useInteractiveLogin)
        {
            if (aadConfig == null)
            {
                throw new ArgumentNullException(nameof(aadConfig));
            }

            _aadConfig = aadConfig;
            _iLogger   = iLogger;

            IClientApplicationBase clientApplication;

            if (useInteractiveLogin)
            {
                var publicClientApplicationOptions = new PublicClientApplicationOptions()
                {
                    AadAuthorityAudience = _aadConfig.AadAuthorityAudience,
                    AzureCloudInstance   = _aadConfig.AzureCloudInstance,
                    ClientId             = _aadConfig.ClientId,
                    RedirectUri          = "urn:ietf:wg:oauth:2.0:oob",
                    TenantId             = _aadConfig.TenantId
                };
                clientApplication = PublicClientApplicationBuilder.CreateWithApplicationOptions(publicClientApplicationOptions)
                                    .Build();
            }
            else
            {
                clientApplication = ConfidentialClientApplicationBuilder.Create(_aadConfig.ClientId)
                                    .WithClientSecret(_aadConfig.ClientSecret)
                                    .WithAuthority(new Uri(_aadConfig.Authority))
                                    .Build();
            }

            _authContext = new GraphMsalAuthenticationProvider(clientApplication, aadConfig.MSALScopes);
        }
Пример #5
0
        //gavdcodeend 01

        //gavdcodebegin 03
        static async System.Threading.Tasks.Task <ExchangeService> ConnectOA(
            string AppId, string TenId)
        {
            ExchangeService exService = new ExchangeService();

            PublicClientApplicationOptions pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = AppId,
                TenantId = TenId
            };

            IPublicClientApplication pcaBuilder = PublicClientApplicationBuilder
                                                  .CreateWithApplicationOptions(pcaOptions).Build();

            string[] exScope = new string[] {
                "https://outlook.office.com/EWS.AccessAsUser.All"
            };

            AuthenticationResult authToken = await
                                             pcaBuilder.AcquireTokenInteractive(exScope).ExecuteAsync();

            exService.Url         = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            exService.Credentials = new OAuthCredentials(authToken.AccessToken);

            return(await System.Threading.Tasks.Task.FromResult(exService));
        }
Пример #6
0
        public static async Task <AuthenticationResult> GetDelegateToken(string ClientId, string TenantId, string Scope = "EWS.AccessAsUser.All")
        {
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ClientId,
                TenantId = TenantId
            };

            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions);

            if (ClientId.Equals("4a03b746-45be-488c-bfe5-0ffdac557d68"))
            {
                pca = pca.WithRedirectUri("http://localhost/SOAPe");
            }

            var app = pca.Build();

            var ewsScopes = new string[] { $"https://outlook.office.com/{Scope}" };

            try
            {
                // Make the interactive token request
                AuthenticationResult authResult = await app.AcquireTokenInteractive(ewsScopes).ExecuteAsync();

                return(authResult);
            }
            catch (Exception ex)
            {
                _lastError = ex;
            }
            return(null);
        }
Пример #7
0
        private IPublicClientApplication CreatePublicClientApplication()
        {
            var options = new PublicClientApplicationOptions();

            _configuration.Bind("AzureAd", options);
            return(PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                   .Build());
        }
        /// <summary>
        /// Function to authenticate against Azure AD using MSAL 3.0
        /// </summary>
        /// <param name="appConfig">Application configuration required for the authentication process</param>
        /// <returns>AuthenticationResult object</returns>
        public static async Task <AuthenticationResult> AuthenticateAsync(PublicClientApplicationOptions appConfig)
        {
            var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(appConfig)
                      .Build();

            DeviceCodeFlow tokenAcquisitionHelper = new DeviceCodeFlow(app);

            return(await tokenAcquisitionHelper.AcquireATokenFromCacheOrDeviceCodeFlowAsync(Scopes));
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MsalAuthenticationService{TAccount, TProviderOptions}"/> class.
        /// </summary>
        /// <param name="options">The options to be passed down to the underlying Authentication library handling the authentication operations.</param>
        /// <param name="protectedStorage">The protect storage where refresh tokens will be stored.</param>
        /// <param name="accountClaimsPrincipalFactory">The <see cref="AccountClaimsPrincipalFactory{TAccount}"/> used to generate the <see cref="ClaimsPrincipal"/> for the user.</param>
        public MsalAuthenticationService(
            IOptionsSnapshot <RemoteAuthenticationOptions <TProviderOptions> > options,
            IProtectedStorage protectedStorage,
            AccountClaimsPrincipalFactory <TAccount> accountClaimsPrincipalFactory) :
            base(options?.Value, accountClaimsPrincipalFactory)
        {
            _clientApplication = (PublicClientApplication)PublicClientApplicationBuilder.CreateWithApplicationOptions(Options.ProviderOptions).Build();

            SetUpSerializationHandlers(protectedStorage);
        }
Пример #10
0
        static async Task Main(string[] args)
        {
            string globalDiscoUrl = "https://globaldisco.crm.dynamics.com/";
            string clientId       = "";
            string account        = "";
            string password       = "";

            var options = new PublicClientApplicationOptions()
            {
                ClientId             = clientId,
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMultipleOrgs,
            };

            var app = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(options)
                      .Build();

            var securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            var authResult = await app.AcquireTokenByUsernamePassword((new[] { $"{globalDiscoUrl}user_impersonation" }), account, securePassword).ExecuteAsync();

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            client.Timeout     = new TimeSpan(0, 2, 0);
            client.BaseAddress = new Uri(globalDiscoUrl);

            HttpResponseMessage response = client.GetAsync("api/discovery/v1.0/Instances", HttpCompletionOption.ResponseHeadersRead).Result;

            var instances = new List <Instance>();

            if (response.IsSuccessStatusCode)
            {
                //Get the response content and parse it.
                string  result = response.Content.ReadAsStringAsync().Result;
                JObject body   = JObject.Parse(result);
                JArray  values = (JArray)body.GetValue("value");

                if (values.HasValues)
                {
                    instances = JsonConvert.DeserializeObject <List <Instance> >(values.ToString());
                }

                Console.WriteLine(result);
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
        private static async Task RunAsync()
        {
            SampleConfiguration config = SampleConfiguration.ReadFromJsonFile("appsettings.json");
            var appConfig = config.PublicClientApplicationOptions;
            var app       = PublicClientApplicationBuilder.CreateWithApplicationOptions(appConfig)
                            .Build();
            var httpClient = new HttpClient();

            MyInformation myInformation = new MyInformation(app, httpClient, config.MicrosoftGraphBaseEndpoint);
            await myInformation.DisplayMeAndMyManagerAsync();
        }
Пример #12
0
        private async void OutlookSign_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // make sure we have an Azure application client ID and a Rebex key (feel free to remove these checks once configured)
                if (ClientId.Contains("00000000-"))
                {
                    throw new ApplicationException("Please configure ClientId in MainWindow.xaml.cs file.");
                }
                if (Rebex.Licensing.Key.Contains("_TRIAL_KEY_"))
                {
                    throw new ApplicationException("Please set a license key in LicenseKey.cs file.");
                }

                // specify options
                var options = new PublicClientApplicationOptions()
                {
                    ClientId = ClientId,
                    TenantId = TenantId,
                    // redirect URI (this one is suitable for desktop and mobile apps with embedded browser)
                    RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient",
                };

                // get an instanca of 'PCA' API
                _publicClientApplication = PublicClientApplicationBuilder
                                           .CreateWithApplicationOptions(options)
                                           .WithParentActivityOrWindow(() => new System.Windows.Interop.WindowInteropHelper(this).Handle)
                                           .Build();

                // authenticate interactively for the scopes we need
                statusLabel.Content = "Authenticating via Office365...";
                AuthenticationResult result = await _publicClientApplication.AcquireTokenInteractive(Scopes).WithPrompt(Prompt.NoPrompt).ExecuteAsync();

                // keep the access token and account info
                _accessToken = result.AccessToken;
                _account     = result.Account;

                // make sure we obtained the user name
                string userName = _account.Username;
                if (userName == null)
                {
                    throw new InvalidOperationException("User name not retrieved. Make sure you specified 'openid' and 'profile' scopes.");
                }

                // retrieve the list of recent messages
                await GetMessageListAsync();
            }
            catch (Exception ex)
            {
                statusLabel.Content = "Failure.";
                MessageBox.Show(this, ex.ToString(), "Error");
            }
        }
Пример #13
0
        private static async Task RunAsync()
        {
            SampleConfiguration config = SampleConfiguration.ReadFromJsonFile("appsettings.json");
            var appConfig = config.PublicClientApplicationOptions;
            var app       = PublicClientApplicationBuilder.CreateWithApplicationOptions(appConfig)
                            .WithAuthority(appConfig.AzureCloudInstance, AadAuthorityAudience.AzureAdMultipleOrgs)                          // work around to MSAL.NET bug #969
                            .Build();
            var httpClient = new HttpClient();

            MyInformation myInformation = new MyInformation(app, httpClient, config.MicrosoftGraphBaseEndpoint);
            await myInformation.DisplayUsersRetryingWhenWrongCredentialsAsync();
        }
Пример #14
0
        public void TestCreateWithOptions()
        {
            var options = new PublicClientApplicationOptions
            {
                Instance = "https://login.microsoftonline.com",
                TenantId = "organizations",
                ClientId = TestConstants.ClientId
            };
            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .Build();

            Assert.AreEqual(TestConstants.AuthorityOrganizationsTenant, pca.Authority);
        }
Пример #15
0
        public void TestCreateWithOptionsAuthorityAudience()
        {
            var options = new PublicClientApplicationOptions
            {
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMultipleOrgs,
                ClientId             = TestConstants.ClientId
            };
            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .Build();

            Assert.AreEqual(TestConstants.AuthorityOrganizationsTenant, pca.Authority);
        }
Пример #16
0
        public static async Task <string> SendEmailMSALAsync()
        {
            // The permission scope required for EWS access
            var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };
            var ClientId  = "";
            var TenantId  = "";


            // Configure the MSAL client to get tokens
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ClientId,
                TenantId = TenantId
            };


            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions).Build();

            var securePassword = new SecureString();

            foreach (char c in "")
            {
                securePassword.AppendChar(c);
            }

            try
            {
                // Make the interactive token request
                var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, "USERNAME", securePassword).ExecuteAsync();

                // Configure the ExchangeService with the access token
                var ewsClient = new ExchangeService();
                ewsClient.Url         = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);

                // Make an EWS call
                EmailMessage email = new EmailMessage(ewsClient);
                email.ToRecipients.Add("*****@*****.**");
                email.Subject = "HelloWorld";
                email.Body    = new MessageBody("This is the first email I've sent by using the EWS Managed API");
                email.Send();
            }
            catch (MsalException x)
            {
                Console.Write(x.Message);
                throw;
            }

            return("sucess");
        }
Пример #17
0
        private static async Task RunAsync()
        {
            // SampleConfiguration config = SampleConfiguration.ReadFromJsonFile("appsettings.json");
            // var appConfig = config.PublicClientApplicationOptions;

            var msalAppOptions = new PublicClientApplicationOptions();

            // Azure AD integration
            // string[] Scopes = new string[] { "https://graph.microsoft.com/.default" };
            // msalAppOptions.ClientId = "9658d0b0-168a-4693-8474-0b3c5c09ec56";
            // msalAppOptions.TenantId = "starflower.onmicrosoft.com";
            // msalAppOptions.AzureCloudInstance = AzureCloudInstance.AzurePublic;

            // AD-FS integration
            // string[] Scopes = new string[] { "profile" };
            // msalAppOptions.ClientId = "2b464e5e-ee58-4e38-8611-17b7406b6217";
            // msalAppOptions.Instance = "https://cosmos.irisflower.pro/adfs/";
            // msalAppOptions.AzureCloudInstance = AzureCloudInstance.None;

            // Custom middleware integration
            string[] Scopes = new string[] { "https://irisflower.onmicrosoft.com/api1/read" };
            msalAppOptions.ClientId           = "2b464e5e-ee58-4e38-8611-17b7406b6217";
            msalAppOptions.Instance           = "https://device-code.azurewebsites.net/";
            msalAppOptions.AzureCloudInstance = AzureCloudInstance.None;

            // Logs
            msalAppOptions.EnablePiiLogging = true;
            msalAppOptions.LogLevel         = LogLevel.Verbose;
            msalAppOptions.IsDefaultPlatformLoggingEnabled = true;
            msalAppOptions.ClientName = "AzureADB2C";

            var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(msalAppOptions)
                      // .WithLogging(MyLoggingMethod, LogLevel.Info,
                      //         enablePiiLogging: true,
                      //         enableDefaultPlatformLogging: true)
                      .Build();

            var tokenAcquisitionHelper = new PublicAppUsingDeviceCodeFlow(app);


            AuthenticationResult authenticationResult = await tokenAcquisitionHelper.AcquireATokenFromCacheOrDeviceCodeFlowAsync(Scopes);

            if (authenticationResult != null)
            {
                Console.WriteLine(authenticationResult.AccessToken);
            }
            else
            {
                Console.WriteLine("Error");
            }
        }
Пример #18
0
        public static async Task FetchAllMessagesOAuthAsync()
        {
            // The permission scope required for EWS access
            var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };
            var ClientId  = "";
            var TenantId  = "";


            // Configure the MSAL client to get tokens
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ClientId,
                TenantId = TenantId
            };


            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions).Build();


            SecureString passwordSecure = new NetworkCredential("", "myPass").SecurePassword;


            // Make the interactive token request
            var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, "USERNAME", passwordSecure).ExecuteAsync();



            using (var client = new ImapClient(new ProtocolLogger("imap.log")))
            {
                client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);

                client.Authenticate(new SaslMechanismOAuth2("username", authResult.AccessToken));

                client.Inbox.Open(FolderAccess.ReadOnly);

                var uids = client.Inbox.Search(SearchQuery.All);

                foreach (var uid in uids)
                {
                    var message = client.Inbox.GetMessage(uid);

                    // write the message to a file
                    message.WriteTo(string.Format("{0}.eml", uid));
                }

                client.Disconnect(true);
            }
        }
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            string       myAddress  = "*****@*****.**";
            SecureString myPassword = new NetworkCredential("", "MYPASSWORD").SecurePassword; // Example. Use a better way to get your password!

            // Using Microsoft.Identity.Client 4.22.0
            // Configure the MSAL client to get tokens
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ConfigurationManager.AppSettings["clientId"],
                TenantId = ConfigurationManager.AppSettings["tenantId"]
            };

            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions).Build();


            // The permission scope required for EWS access
            var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };

            var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, myAddress, myPassword).ExecuteAsync();

            var token = authResult.AccessToken;

            ExchangeService ews = new ExchangeService();

            ews.Credentials = new OAuthCredentials(token);

            ews.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");


            // Sending Mail
            EmailMessage email = new EmailMessage(ews);

            email.ToRecipients.Add("*****@*****.**");
            email.Subject = "HelloWorld";
            email.Body    = new MessageBody("This is the first email I've sent by using the EWS Managed API");
            email.Send();

            // Receiving Mail
            FolderId SharedMailbox = new FolderId(WellKnownFolderName.Inbox, myAddress);
            ItemView itemView      = new ItemView(1000);
            var      mails         = ews.FindItems(SharedMailbox, itemView);

            foreach (var mail in mails)
            {
                Console.WriteLine(mail.Subject);
            }
        }
Пример #20
0
        public void WithClientCapabilitiesViaOptions()
        {
            var options = new PublicClientApplicationOptions
            {
                Instance           = "https://login.microsoftonline.com",
                TenantId           = "organizations",
                ClientId           = TestConstants.ClientId,
                ClientCapabilities = new[] { "cp1", "cp2" }
            };

            var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .Build();

            CollectionAssert.AreEquivalent(new string[] { "cp1", "cp2" }, app.AppConfig.ClientCapabilities.ToList());
        }
Пример #21
0
        public void TestAuthorityPermutations(
            AzureCloudInstance cloudInstance,
            AadAuthorityAudience audience,
            string expectedAuthority)
        {
            var options = new PublicClientApplicationOptions
            {
                AzureCloudInstance   = cloudInstance,
                AadAuthorityAudience = audience,
                ClientId             = TestConstants.ClientId
            };
            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .Build();

            Assert.AreEqual(expectedAuthority, pca.Authority);
        }
        public void CacheSynchronizationWithDefaultCCA()
        {
            //Validate CacheSynchronizationEnabled when app is created from ApplicaitonOptions for CCA
            var options = new ConfidentialClientApplicationOptions()
            {
                ClientSecret = "secret",
                ClientId     = TestConstants.ClientId,
            };
            var app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build();

            Assert.IsFalse((app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled);

            options = new ConfidentialClientApplicationOptions
            {
                ClientId     = TestConstants.ClientId,
                ClientSecret = "secret",
                EnableCacheSynchronization = false
            };
            app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build();
            Assert.AreEqual(false, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled);

            options = new ConfidentialClientApplicationOptions
            {
                ClientId     = TestConstants.ClientId,
                ClientSecret = "secret",
                EnableCacheSynchronization = true
            };
            app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options).Build();
            Assert.AreEqual(true, (app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled);

            //Validate CacheSynchronizationEnabled is false by default when app is created from ConfidentialClientApplicationBuilder
            app = ConfidentialClientApplicationBuilder.Create(Guid.NewGuid().ToString()).WithClientSecret(TestConstants.ClientSecret).BuildConcrete();
            Assert.IsFalse((app.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled);

            //Validate CacheSynchronizationEnabled when app is created from ApplicaitonOptions for PCA
            var options2 = new PublicClientApplicationOptions()
            {
                ClientId = TestConstants.ClientId
            };
            var app2 = PublicClientApplicationBuilder.CreateWithApplicationOptions(options2).Build();

            Assert.IsTrue((app2.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled);

            //Validate CacheSynchronizationEnabled is true by default when app is created from PublicClientApplicationBuilder
            app2 = PublicClientApplicationBuilder.Create(Guid.NewGuid().ToString()).BuildConcrete();
            Assert.IsTrue((app2.AppConfig as ApplicationConfiguration).CacheSynchronizationEnabled);
        }
Пример #23
0
        public void EnsureCreatePublicClientWithAzureAdMyOrgAndValidTenantSucceeds()
        {
            const string tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";

            var options = new PublicClientApplicationOptions
            {
                AzureCloudInstance   = AzureCloudInstance.AzurePublic,
                AadAuthorityAudience = AadAuthorityAudience.AzureAdMyOrg,
                TenantId             = tenantId,
                ClientId             = TestConstants.ClientId
            };

            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .Build();

            Assert.AreEqual($"https://login.microsoftonline.com/{tenantId}/", pca.Authority);
        }
Пример #24
0
        private void buttonGetInboxMessages_Click(object sender, EventArgs e)
        {
            Action action = new Action(async() =>
            {
                // Configure the MSAL client to get tokens
                var pcaOptions = new PublicClientApplicationOptions
                {
                    ClientId = textBoxAppId.Text,
                    TenantId = textBoxTenantId.Text
                };

                var pca = PublicClientApplicationBuilder
                          .CreateWithApplicationOptions(pcaOptions).Build();

                var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };

                try
                {
                    // Make the interactive token request
                    var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();

                    // Configure the ExchangeService with the access token
                    var ewsClient         = new ExchangeService(ExchangeVersion.Exchange2016);
                    ewsClient.Url         = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                    ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);

                    // Make an EWS call
                    var items = ewsClient.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
                    foreach (var item in items)
                    {
                        WriteToResults($"{item.DateTimeReceived}: {item.Subject}");
                    }
                }
                catch (MsalException ex)
                {
                    WriteToResults($"Error acquiring access token: {ex}");
                }
                catch (Exception ex)
                {
                    WriteToResults($"Error: {ex}");
                }
            });

            System.Threading.Tasks.Task.Run(action);
        }
Пример #25
0
        static async Task TestIMAP(string ClientId, string TenantId)
        {
            // Configure the MSAL client to get tokens
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ClientId,
                TenantId = TenantId
            };

            Console.WriteLine("Building application");
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions)
                      .WithRedirectUri("http://localhost")
                      .Build();

            var imapScope = new string[] { $"https://{_imapEndpoint}/IMAP.AccessAsUser.All" };

            try
            {
                // Make the interactive token request
                Console.WriteLine("Requesting access token (user must log-in via browser)");
                var authResult = await pca.AcquireTokenInteractive(imapScope).ExecuteAsync();

                if (String.IsNullOrEmpty(authResult.AccessToken))
                {
                    Console.WriteLine("No token received");
                }
                else
                {
                    Console.WriteLine($"Token received for {authResult.Account.Username}");

                    // Use the token to connect to IMAP service
                    RetrieveMessages(authResult);
                }
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
            }
            Console.WriteLine("Finished");
        }
        public IPublicClientApplication CreatePublicClientApplication()
        {
            var options = serviceProvider
                          .GetRequiredService <IOptions <PublicClientApplicationOptions> >()
                          .Value;
            var builder = PublicClientApplicationBuilder
                          .CreateWithApplicationOptions(options);

            ConfigureBuilder(builder);
            var app = builder.Build();
            var cacheStorageProvider = serviceProvider.GetService <MsalTokenCacheProvider>();

            if (cacheStorageProvider is not null)
            {
                cacheStorageProvider.RegisterCache(app.UserTokenCache);
            }
            return(app);
        }
        public async Task Init()
        {
            if (_publicClientApplication != null)
            {
                return;
            }

            var options = new PublicClientApplicationOptions
            {
                TenantId           = TenantId,
                ClientId           = ClientId,
                AzureCloudInstance = AzureCloudInstance.AzurePublic
            };

            _publicClientApplication = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).Build();
            var builder = _publicClientApplication.AcquireTokenWithDeviceCode(Scopes, DeviceCodeResultCallback);
            var result  = await builder.ExecuteAsync();
        }
Пример #28
0
        public void TestConstructor_WithDebugLoggingCallbackAndAppConfig()
        {
            // Ensure that values in the options are not reset to defaults when not sent into WithLogging
            var options = new PublicClientApplicationOptions
            {
                ClientId         = TestConstants.ClientId,
                LogLevel         = LogLevel.Error,
                EnablePiiLogging = true,
                IsDefaultPlatformLoggingEnabled = true
            };

            var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
                      .WithLogging((level, message, pii) => { }).Build();

            Assert.AreEqual(LogLevel.Error, pca.AppConfig.LogLevel);
            Assert.IsTrue(pca.AppConfig.EnablePiiLogging);
            Assert.IsTrue(pca.AppConfig.IsDefaultPlatformLoggingEnabled);
        }
Пример #29
0
        public async System.Threading.Tasks.Task AuthenticateClientDelegatePermission()
        {
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ConfigurationManager.AppSettings["APP_ID"],
                TenantId = ConfigurationManager.AppSettings["TENANT_ID"]
            };

            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions).Build();

            var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };

            try
            {
                // Make the interactive token request
                var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();

                // Configure the ExchangeService with the access token
                var ewsClient = new ExchangeService();
                ewsClient.Url         = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);

                // Make an EWS call
                var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
                foreach (var folder in folders)
                {
                    Console.WriteLine($"Folder: {folder.DisplayName}");
                }
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex.ToString()}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.ToString()}");
            }
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Hit any key to exit...");
                Console.ReadKey();
            }
        }
Пример #30
0
        static async Task TestSMTP(string ClientId, string TenantId, string EmlFile = "")
        {
            // Configure the MSAL client to get tokens
            var pcaOptions = new PublicClientApplicationOptions
            {
                ClientId = ClientId,
                TenantId = TenantId
            };

            Console.WriteLine("Building application");
            var pca = PublicClientApplicationBuilder
                      .CreateWithApplicationOptions(pcaOptions)
                      .WithRedirectUri("http://localhost")
                      .Build();

            var smtpScope = new string[] { "https://outlook.office.com/SMTP.Send" };

            try
            {
                // Make the interactive token request
                Console.WriteLine("Requesting access token (user must log-in via browser)");
                var authResult = await pca.AcquireTokenInteractive(smtpScope).ExecuteAsync();

                if (String.IsNullOrEmpty(authResult.AccessToken))
                {
                    Console.WriteLine("No token received");
                    return;
                }
                Console.WriteLine($"Token received for {authResult.Account.Username}");

                // Use the token to connect to SMTP service
                SendMessageToSelf(authResult, EmlFile);
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
            }
            Console.WriteLine("Finished");
        }