Exemple #1
0
        private IPublicClientApplication CreatePca()
        {
            string clientId = GetClientId();
            bool   msaPt    = IsMsaPassthroughConfigured();

            var pca = PublicClientApplicationBuilder
                      .Create(clientId)
                      .WithAuthority(this.authorityCbx.Text)
                      .WithExperimentalFeatures(true)
                      .WithDesktopFeatures()
                      .WithBroker(this.useBrokerChk.Checked)
                      // there is no need to construct the PCA with this redirect URI,
                      // but WAM uses it. We could enforce it.
                      //.WithRedirectUri($"ms-appx-web://microsoft.aad.brokerplugin/{clientId}")
                      .WithMsaPassthrough(msaPt)
                      .WithLogging((x, y, z) => Debug.WriteLine($"{x} {y}"), LogLevel.Verbose, true)
                      .Build();

            BindCache(pca.UserTokenCache, UserCacheFile);
            return(pca);
        }
Exemple #2
0
        private static async Task AsyncMain()
        {
            //var app = DeviceCodeProvider.CreateClientApplication("<InsertClientId>", new FileBasedTokenStorageProvider());
            var app  = PublicClientApplicationBuilder.Create("<clientId>").Build();
            var auth = new DeviceCodeProvider(app, new string[] { "User.Read" });

            var handlers = GraphClientFactory.CreateDefaultHandlers(auth).ToList();

            handlers.Insert(1, new CompressionHandler());
            handlers.Add(new DemoLoggingHandler());


            var httpClient = GraphClientFactory.Create(handlers, "v1.0/");

            var userResponse = await httpClient.GetStringAsync("me");

            Console.WriteLine();
            Console.WriteLine(userResponse);

            Console.Read();
        }
Exemple #3
0
        /// <summary>
        /// Creates a new DeviceCodeCredential with the specifeid options, which will authenticate users with the specified application.
        /// </summary>
        /// <param name="deviceCodeCallback">The callback to be executed to display the device code to the user</param>
        /// <param name="clientId">The client id of the application to which the users will authenticate</param>
        /// <param name="tenantId">The tenant id of the application to which users will authenticate.  This can be unspecified for multi-tenanted applications.</param>
        /// <param name="options">The client options for the newly created DeviceCodeCredential</param>
        public DeviceCodeCredential(Func <DeviceCodeInfo, CancellationToken, Task> deviceCodeCallback, string clientId, string tenantId = default, AzureCredentialOptions options = default)
        {
            _clientId = clientId ?? throw new ArgumentNullException(nameof(clientId));

            _deviceCodeCallback = deviceCodeCallback ?? throw new ArgumentNullException(nameof(deviceCodeCallback));

            _options = options ?? new AzureCredentialOptions();

            _pipeline = HttpPipelineBuilder.Build(_options);

            _clientDiagnostics = new ClientDiagnostics(options);

            var pubAppBuilder = PublicClientApplicationBuilder.Create(_clientId).WithHttpClientFactory(new HttpPipelineClientFactory(_pipeline)).WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient");

            if (!string.IsNullOrEmpty(tenantId))
            {
                pubAppBuilder = pubAppBuilder.WithTenantId(tenantId);
            }

            _pubApp = pubAppBuilder.Build();
        }
Exemple #4
0
        private static async Task <AuthenticationResult> AcquireTokenForLabUserAsync()
        {
            var labResponse = await LabUserHelper.GetSpecificUserAsync(TestConstants.OBOUser).ConfigureAwait(false);

            var msalPublicClient = PublicClientApplicationBuilder
                                   .Create(TestConstants.OBOClientSideClientId)
                                   .WithAuthority(labResponse.Lab.Authority, TestConstants.Organizations)
                                   .Build();

            AuthenticationResult authResult = await msalPublicClient
                                              .AcquireTokenByUsernamePassword(
                TestConstants.OBOApiScope,
                TestConstants.OBOUser,
                new NetworkCredential(
                    TestConstants.OBOUser,
                    labResponse.User.GetOrFetchPassword()).SecurePassword)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

            return(authResult);
        }
        // Get an access token for the given context and resourceId.
        // An attempt is first made to acquire the token silently.
        // If that fails, then we try to acquire the token by prompting the user.
        public static IAuthenticationProvider GetIAuthenticationProvider()
        {
            if (authProvider == null)
            {
                try
                {
                    IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
                                                                       .Create(clientId)
                                                                       .Build();

                    authProvider = new InteractiveAuthenticationProvider(publicClientApplication, scopesArray);
                    return(authProvider);
                }

                catch (ServiceException ex)
                {
                    throw new Exception("Could not create an IAuthenticationProvider: " + ex.Message);
                }
            }
            return(authProvider);
        }
 private static void AddRuntimeSupportForWam(PublicClientApplicationBuilder builder)
 {
     if (DesktopOsHelper.IsWin10OrServerEquivalent())
     {
         builder.Config.BrokerCreatorFunc =
             (uiParent, appConfig, logger) =>
         {
             logger.Info("WAM supported OS.");
             return(new RuntimeBroker(uiParent, appConfig, logger));
         };
     }
     else
     {
         builder.Config.BrokerCreatorFunc =
             (uiParent, appConfig, logger) =>
         {
             logger.Info("Not a Win10 machine. WAM is not available");
             return(new NullBroker(logger));
         };
     }
 }
        private B2CAuthenticationService()
        {
            // default redirectURI; each platform specific project will have to override it with its own
            var builder = PublicClientApplicationBuilder.Create(B2CConstants.ClientID)
                          .WithB2CAuthority(B2CConstants.AuthoritySignInSignUp)
                          .WithIosKeychainSecurityGroup(B2CConstants.IOSKeyChainGroup)
                          // .WithRedirectUri("http://localhost");
                          .WithRedirectUri(B2CConstants.RedirectUri);

            // Android implementation is based on https://github.com/jamesmontemagno/CurrentActivityPlugin
            // iOS implementation would require to expose the current ViewControler - not currently implemented as it is not required
            // UWP does not require this
            var windowLocatorService = DependencyService.Get <IParentWindowLocatorService>();

            if (windowLocatorService != null)
            {
                builder = builder.WithParentActivityOrWindow(() => windowLocatorService?.GetCurrentParentWindow());
            }

            _pca = builder.Build();
        }
        static async Task Main(string[] args)
        {
            // use an Azure AD app in your demo tenant with http://localhost as a redirect URI under "Mobile and Desktop Applications"
            // (it won't work if it's under Web, which is the default!)
            // and the following delegated permissions:
            // - GroupMember.Read.All
            // - User.Read.All
            // When you run this, sign in with your demo tenant administrator credentials.
            string clientId = AppSettings.LoadAppSettings().ClientId;
            string tenantId = AppSettings.LoadAppSettings().TenantId;

            var publicClientApp = PublicClientApplicationBuilder.Create(clientId)
                                  .WithRedirectUri("http://localhost")
                                  .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
                                  .Build();

            var authProvider        = new InteractiveAuthenticationProvider(publicClientApp);
            var _graphServiceClient = new GraphServiceClient(authProvider);
            var users = new Users(_graphServiceClient);
            await users.AddUsers();
        }
Exemple #9
0
        public async Task <TokenModel> Login(string clientId, string userName, string password)
        {
            var app = PublicClientApplicationBuilder.Create(clientId)
                      .WithAuthority("https://login.microsoftonline.com/organizations")
                      .Build();

            var scopes = new List <string> {
                "https://analysis.windows.net/powerbi/api/.default"
            };

            SecureString sec_pass = new SecureString();

            Array.ForEach(password.ToArray(), sec_pass.AppendChar);
            sec_pass.MakeReadOnly();

            var token = await app.AcquireTokenByUsernamePassword(scopes, userName, sec_pass).ExecuteAsync();

            return(new TokenModel {
                Token = token.AccessToken, ExpiredDateTimeUtc = token.ExpiresOn.UtcDateTime
            });
        }
    public async void Login()
    {
        string        clientId = "<client-id-guid>";
        List <string> scopes   = new List <string> {
            "User.ReadBasic.All"
        };

        var clientApplication = PublicClientApplicationBuilder
                                .Create(clientId)
                                .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs)
                                .Build();


        var authProvider = new DeviceCodeProvider(clientApplication, scopes, HandleDeviceCodeMessage);

        var graphClient = new GraphServiceClient(authProvider);

        User profile = await graphClient.Me.Request().GetAsync();

        Username.Text = profile.DisplayName;
    }
Exemple #11
0
        public void TestConstructor()
        {
            var pca = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                      .Build();

            Assert.AreEqual(MsalTestConstants.ClientId, pca.AppConfig.ClientId);
            Assert.IsNotNull(pca.UserTokenCache);

            // Validate Defaults
            Assert.AreEqual(LogLevel.Info, pca.AppConfig.LogLevel);
            Assert.AreEqual(MsalTestConstants.ClientId, pca.AppConfig.ClientId);
            Assert.IsNotNull(pca.AppConfig.ClientName);
            Assert.IsNotNull(pca.AppConfig.ClientVersion);
            Assert.IsFalse(pca.AppConfig.EnablePiiLogging);
            Assert.IsNull(pca.AppConfig.HttpClientFactory);
            Assert.IsFalse(pca.AppConfig.IsDefaultPlatformLoggingEnabled);
            Assert.IsNull(pca.AppConfig.LoggingCallback);
            Assert.AreEqual(PlatformProxyFactory.CreatePlatformProxy(null).GetDefaultRedirectUri(MsalTestConstants.ClientId), pca.AppConfig.RedirectUri);
            Assert.IsNull(pca.AppConfig.TenantId);
            Assert.IsNull(pca.AppConfig.TelemetryConfig);
        }
Exemple #12
0
        public static async Task <MsalProvider> CreateMsalProviderAsync(string clientid, string redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient", string[] scopes = null)
        {
            var client = PublicClientApplicationBuilder.Create(clientid)
                         .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
                         .WithRedirectUri(redirectUri)
                         .WithClientName(ProviderManager.ClientName)
                         .WithClientVersion(Assembly.GetExecutingAssembly().GetName().Version.ToString())
#if __ANDROID__
                         .WithParentActivityOrWindow(() => Uno.UI.ContextHelper.Current as Android.App.Activity)
#endif
                         .Build();

            if (scopes == null)
            {
                scopes = new string[] { string.Empty };
            }

            var provider = new InteractiveAuthenticationProvider(client, scopes);

            return(await MsalProvider.CreateAsync(client, provider));
        }
Exemple #13
0
        public MsalClient(
            IAppSettings appSettings,
            IFileWriter fileWriter,
            HttpClient httpClient,
            ITelemetry telemetry)
        {
            Guard.IsNotNull(appSettings, nameof(appSettings));
            Guard.IsNotNull(fileWriter, nameof(fileWriter));
            Guard.IsNotNull(httpClient, nameof(httpClient));
            Guard.IsNotNull(telemetry, nameof(telemetry));

            _clientId      = appSettings.MsaClientId;
            _fileWriter    = fileWriter;
            _httpClient    = httpClient;
            _telemetry     = telemetry;
            _msalSdkClient = PublicClientApplicationBuilder
                             .Create(_clientId)
                             .WithAuthority(Authority)
                             .WithRedirectUri(RedirectUri)
                             .Build();
        }
Exemple #14
0
        internal SharedTokenCacheProvider(StorageCreationPropertiesBuilder builder, IConfiguration config = null, ILogger logger = null)
        {
            _logger = logger;
            _config = config ?? new ConfigurationBuilder().AddEnvironmentVariables().Build();

            var authority = _config.GetValue <string>(Constants.AadAuthorityEnvName) ??
                            string.Format(CultureInfo.InvariantCulture,
                                          AadAuthority.AadCanonicalAuthorityTemplate,
                                          AadAuthority.DefaultTrustedHost,
                                          "common");

            _app = PublicClientApplicationBuilder
                   .Create(AzureCliClientId)
                   .WithAuthority(new Uri(authority))
                   .Build();

            var cacheStore = new MsalCacheStorage(builder.Build());

            _cacheHelper = new MsalCacheHelper(_app.UserTokenCache, cacheStore);
            _cacheHelper.RegisterCache(_app.UserTokenCache);
        }
        public MsalPublicClient(HttpPipeline pipeline, string clientId, string tenantId = default, string redirectUrl = default, bool attachSharedCache = false)
        {
            PublicClientApplicationBuilder pubAppBuilder = PublicClientApplicationBuilder.Create(clientId).WithHttpClientFactory(new HttpPipelineClientFactory(pipeline));

            if (!string.IsNullOrEmpty(tenantId))
            {
                pubAppBuilder = pubAppBuilder.WithTenantId(tenantId);
            }

            if (!string.IsNullOrEmpty(redirectUrl))
            {
                pubAppBuilder = pubAppBuilder.WithRedirectUri(redirectUrl);
            }

            _client = pubAppBuilder.Build();

            if (attachSharedCache)
            {
                _cacheReader = new MsalCacheReader(_client.UserTokenCache, Constants.SharedTokenCacheFilePath, Constants.SharedTokenCacheAccessRetryCount, Constants.SharedTokenCacheAccessRetryDelay);
            }
        }
        public void ClientIdMustBeAGuid()
        {
            var ex = AssertException.Throws <MsalClientException>(
                () => PublicClientApplicationBuilder.Create("http://my.app")
                .WithAuthority(TestConstants.AadAuthorityWithTestTenantId)
                .Build());

            Assert.AreEqual(MsalError.ClientIdMustBeAGuid, ex.ErrorCode);

            ex = AssertException.Throws <MsalClientException>(
                () => PublicClientApplicationBuilder.Create("http://my.app")
                .WithAuthority(TestConstants.B2CAuthority)
                .Build());

            Assert.AreEqual(MsalError.ClientIdMustBeAGuid, ex.ErrorCode);

            // ADFS does not have this constraint
            PublicClientApplicationBuilder.Create("http://my.app")
            .WithAuthority(new Uri(TestConstants.ADFSAuthority))
            .Build();
        }
Exemple #17
0
        static void Main(string[] args)
        {
            string tenant    = "karoth.onmicrosoft.com";
            string clientId  = "";
            string tenantId  = "";
            string authority = $"https://login.microsoftonline.com/{tenant}";
            // Create MSAL context using AAD authority
            IPublicClientApplication app;

            app = PublicClientApplicationBuilder.Create(clientId)
                  .WithRedirectUri("http://localhost") // needs to be manually configured in App registration authenticatoin block!
                  .Build();
            //app = PublicClientApplicationBuilder.Create(clientId)
            //    .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
            //    .Build();
            var scopes = new string[] { "user.read" };
            var token  = app.AcquireTokenInteractive(scopes)
                         .ExecuteAsync().GetAwaiter().GetResult();

            Console.WriteLine(token);
        }
Exemple #18
0
        [TestCategory(TestCategories.Regression)] //https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2706
        public async Task NullAndIosBroker_GetAccounts_Async(Type brokerType)
        {
            using (var harness = CreateTestHarness())
            {
                // Arrange
                var broker  = CreateBroker(brokerType);
                var builder = PublicClientApplicationBuilder
                              .Create(TestConstants.ClientId)
                              .WithHttpManager(harness.HttpManager);

                builder.Config.BrokerCreatorFunc = (parent, config, logger) => { return(new NullBroker(logger)); };

                var app = builder.WithBroker(true).BuildConcrete();

                // Act
                var accounts = await app.GetAccountsAsync().ConfigureAwait(false);

                // Assert
                Assert.IsFalse(accounts.Any());
            }
        }
        static async Task Main(string[] args)
        {
            string[] scopes = new string[] {
                "User.Read"
            };

            var app = PublicClientApplicationBuilder
                      .Create(_clientId)
                      .WithRedirectUri("http://localhost")
                      .Build();

            var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

            var token = result.AccessToken;

            string profileJson = await "https://graph.microsoft.com/v1.0/me"
                                 .WithOAuthBearerToken(token)
                                 .GetStringAsync();

            Console.WriteLine(profileJson);
        }
    public async void Login()
    {
        string        clientId = "<client-id-guid>";
        List <string> scopes   = new List <string> {
            "User.ReadBasic.All"
        };

        var clientApplication = PublicClientApplicationBuilder
                                .Create(clientId)
                                .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs)
                                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                                .Build();

        var authProvider = new InteractiveAuthenticationProvider(clientApplication, scopes);

        var graphClient = new GraphServiceClient(authProvider);

        User profile = await graphClient.Me.Request().GetAsync();

        Username.Text = profile.UserPrincipalName;
    }
        private static async Task FetchTokenAndCallProtectedApiAsync()
        {
            IPublicClientApplication pca = PublicClientApplicationBuilder
                                           .Create(ClientId)
                                           .WithRedirectUri(DefaultOsBrowserWebUi.FindFreeLocalhostRedirectUri()) // required for DefaultOsBrowser
                                           .Build();

            AuthenticationResult authResult = await FetchTokenFromCacheAsync(pca).ConfigureAwait(false);

            if (authResult == null)
            {
                authResult = await FetchTokenInteractivelyAsync(pca).ConfigureAwait(false);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Token acquired for: " + authResult.Account.Username);
            Console.ResetColor();

            // Now use the token to access a protected API
            await CallGraphAsync(authResult.AccessToken).ConfigureAwait(false);
        }
Exemple #22
0
        private async Task <IPublicClientApplication> GetPCAAsync(bool useLocalHost = false)
        {
            var helper = await GetMsalCacheHelperAsync().ConfigureAwait(false);

            var publicClientBuilder = PublicClientApplicationBuilder.Create(this.clientId)
                                      .WithAuthority(this.authority);

            if (useLocalHost)
            {
                publicClientBuilder.WithRedirectUri("http://localhost");
            }
            else
            {
                publicClientBuilder.WithRedirectUri(NativeClientRedirect);
            }

            var publicClient = publicClientBuilder.Build();

            helper?.RegisterCache(publicClient.UserTokenCache);
            return(publicClient);
        }
Exemple #23
0
        [WorkItem(1456)] // Fix for https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1456
        public async Task AcquireTokenSilent_OverrideWithCommon_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(ClientApplicationBase.DefaultAuthority)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCacheWithOneAccessToken(app.UserTokenCacheInternal.Accessor);
                var cacheAccess = app.UserTokenCache.RecordAccess();

                var acc = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();

                AuthenticationResult result = await app
                                              .AcquireTokenSilent(TestConstants.s_scope, acc)
                                              .WithAuthority(ClientApplicationBase.DefaultAuthority) // this override should do nothing, it's mean to specify a tenant id
                                              .ExecuteAsync().ConfigureAwait(false);
            }
        }
        public async Task AcquireTokenSilent_LoginHint_NoAccountAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                PublicClientApplication app = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                                              .WithAuthority(new Uri(MsalTestConstants.AuthorityTestTenant), true)
                                              .WithHttpManager(httpManager)
                                              .WithTelemetry(new TraceTelemetryConfig())
                                              .BuildConcrete();
                var tokenCacheHelper = new TokenCacheHelper();
                tokenCacheHelper.PopulateCache(app.UserTokenCacheInternal.Accessor);

                var exception = await AssertException.TaskThrowsAsync <MsalUiRequiredException>(() => app.AcquireTokenSilent(
                                                                                                    MsalTestConstants.Scope.ToArray(),
                                                                                                    "*****@*****.**")
                                                                                                .WithAuthority(app.Authority, false)
                                                                                                .ExecuteAsync()).ConfigureAwait(false);

                Assert.AreEqual(MsalError.NoAccountForLoginHint, exception.ErrorCode);
            }
        }
        static async Task Main(string[] args)
        {
            IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId)
                                           .WithB2CAuthority(authority)
                                           .WithRedirectUri("http://localhost")
                                           .Build();

            try
            {
                Console.WriteLine("Authenticating user ...");
                AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

                Console.WriteLine(result.IdToken);
            }
            catch (MsalException exc)
            {
                Console.WriteLine(exc.Message);
            }

            Console.Read();
        }
        /// <summary>
        /// When the Web API needs consent, it can sent a 403 with information in the WWW-Authenticate header in
        /// order to challenge the user
        /// </summary>
        /// <param name="response">HttpResonse received from the service</param>
        /// <returns></returns>
        private async Task HandleChallengeFromWebApi(HttpResponseMessage response, IAccount account)
        {
            AuthenticationHeaderValue bearer     = response.Headers.WwwAuthenticate.First(v => v.Scheme == "Bearer");
            IEnumerable <string>      parameters = bearer.Parameter.Split(',').Select(v => v.Trim()).ToList();
            string clientId = GetParameter(parameters, "clientId");
            string claims   = GetParameter(parameters, "claims");

            string[] scopes         = GetParameter(parameters, "scopes")?.Split(',');
            string   proposedAction = GetParameter(parameters, "proposedAction");

            string loginHint            = account?.Username;
            string domainHint           = IsConsumerAccount(account) ? "consumers" : "organizations";
            string extraQueryParameters = $"claims={claims}&domainHint={domainHint}";

            if (proposedAction == "forceRefresh")
            {
                // Removes the account, but then re-signs-in
                await _app.RemoveAsync(account);

                await _app.AcquireTokenInteractive(scopes)
                .WithPrompt(Prompt.Consent)
                .WithLoginHint(loginHint)
                .WithExtraQueryParameters(extraQueryParameters)
                .WithAuthority(_app.Authority)
                .ExecuteAsync()
                .ConfigureAwait(false);
            }
            else if (proposedAction == "consent")
            {
                IPublicClientApplication pca = PublicClientApplicationBuilder.Create(clientId)
                                               .Build();
                await pca.AcquireTokenInteractive(scopes)
                .WithPrompt(Prompt.Consent)
                .WithLoginHint(loginHint)
                .WithExtraQueryParameters(extraQueryParameters)
                .WithAuthority(pca.Authority)
                .ExecuteAsync()
                .ConfigureAwait(false);
            }
        }
        public async Task AcquireTokenByIntegratedWindowsAuthTest_ManagedUser_DiscoveryFailed_ThrowsExceptionAsync()
        {
            // Arrange
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(
                            "{\"ver\":\"1.0\"," +
                            "\"account_type\":\"Managed\"," +
                            "\"domain_name\":\"some_domain.onmicrosoft.com\"," +
                            "\"cloud_audience_urn\":\"urn:federation:MicrosoftOnline\"," +
                            "\"cloud_instance_name\":\"login.microsoftonline.com\"}")
                    }
                });

                PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                              .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                                              .WithHttpManager(httpManager)
                                              .BuildConcrete();

                // Act
                MsalServiceException exception = await AssertException.TaskThrowsAsync <MsalServiceException>(
                    async() => await app
                    .AcquireTokenByIntegratedWindowsAuth(TestConstants.s_scope)
                    .WithUsername(TestConstants.s_user.Username)
                    .ExecuteAsync(CancellationToken.None)
                    .ConfigureAwait(false)).ConfigureAwait(false);

                // Assert
                Assert.AreEqual(MsalError.UserRealmDiscoveryFailed, exception.ErrorCode);
                Assert.AreEqual(HttpStatusCode.NotFound, (HttpStatusCode)exception.StatusCode);
            }
        }
Exemple #28
0
        static async Task DoIt()
        {
            AppCoordinates.AppCoordinates v1App = AppCoordinates.PreRegisteredApps.GetV1App(useInMsal: true);
            string resource = AppCoordinates.PreRegisteredApps.MsGraph;

            string[] scopes = new string[] { resource + "/user.read" };

            string cacheFolder         = Path.GetFullPath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"..\..\..\..");
            string adalV3cacheFileName = Path.Combine(cacheFolder, "cacheAdalV3.bin");
            string msalCacheFileName   = Path.Combine(cacheFolder, "cacheMsal.bin");

            AuthenticationResult result;

            IPublicClientApplication app;

            app = PublicClientApplicationBuilder.Create(v1App.ClientId)
                  .WithAuthority(v1App.Authority)
                  .Build();
            FilesBasedTokenCacheHelper.EnableSerialization(app.UserTokenCache,
                                                           msalCacheFileName,
                                                           adalV3cacheFileName);
            var accounts = await app.GetAccountsAsync();

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

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Using MSALV4.x got token for '{result.Account.Username}' from the cache");
                Console.ResetColor();
            }
            catch (MsalUiRequiredException ex)
            {
                result = await app.AcquireTokenInteractive(scopes)
                         .ExecuteAsync();

                Console.WriteLine($"Using MSALV4.x got token for '{result.Account.Username}' without the cache");
            }
        }
Exemple #29
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule <ApplicationModule>();
            builder.RegisterModule <PersistenceModule>();

            builder.RegisterType <Mediator>().As <IMediator>().InstancePerLifetimeScope();

            // request & notification handlers
            builder.Register <ServiceFactory>(context =>
            {
                var c = context.Resolve <IComponentContext>();

                return(t => c.Resolve(t));
            });

            builder.RegisterAssemblyTypes(typeof(GetPaymentByIdQuery).Assembly).AsImplementedInterfaces(); // via assembly scan

            builder.Register(c => PublicClientApplicationBuilder
                             .Create(ServiceConstants.MSAL_APPLICATION_ID)
                             .WithRedirectUri($"msal{ServiceConstants.MSAL_APPLICATION_ID}://auth")
                             .WithIosKeychainSecurityGroup("com.microsoft.adalcache")
                             .Build());

            builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(t => t.Name.EndsWith("Service", StringComparison.CurrentCultureIgnoreCase))
            .Where(t => !t.Name.Equals("NavigationService", StringComparison.CurrentCultureIgnoreCase))
            .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(t => !t.Name.StartsWith("DesignTime", StringComparison.CurrentCultureIgnoreCase))
            .Where(t => t.Name.EndsWith("ViewModel", StringComparison.CurrentCultureIgnoreCase))
            .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(t => !t.Name.StartsWith("DesignTime", StringComparison.CurrentCultureIgnoreCase))
            .Where(t => t.Name.EndsWith("ViewModel", StringComparison.CurrentCultureIgnoreCase))
            .AsSelf();

            CultureHelper.CurrentCulture = CultureInfo.CreateSpecificCulture(new SettingsFacade(new SettingsAdapter()).DefaultCulture);
        }
        private async Task <PublicClientApplication> SetupAndAcquireOnceAsync(
            MockHttpAndServiceBundle httpManagerAndBundle,
            int httpStatusCode,
            int?retryAfterInSeconds,
            TokenResponseType tokenResponseType)
        {
            Trace.WriteLine("1. Setup test");
            var httpManager = httpManagerAndBundle.HttpManager;

            PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                          .WithHttpManager(httpManager)
                                          .BuildConcrete();

            new TokenCacheHelper().PopulateCache(app.UserTokenCacheInternal.Accessor, expiredAccessTokens: true);

            var tokenResponse = httpManager.AddAllMocks(tokenResponseType);

            UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, httpStatusCode, retryAfterInSeconds);

            if (httpStatusCode >= 500 && httpStatusCode < 600 && !retryAfterInSeconds.HasValue)
            {
                var response2 = httpManager.AddTokenResponse(
                    tokenResponseType, s_throttlingHeader);
                UpdateStatusCodeAndHeaders(response2.ResponseMessage, httpStatusCode, retryAfterInSeconds);
            }

            var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();

            Trace.WriteLine("2. First failing call ");
            var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync(),
                allowDerived : true)
                     .ConfigureAwait(false);

            Assert.AreEqual(0, httpManager.QueueSize, "No more requests expected");
            Assert.AreEqual(httpStatusCode, ex.StatusCode);
            Assert.AreEqual(tokenResponseType == TokenResponseType.InvalidGrant, ex is MsalUiRequiredException);

            return(app);
        }