Native applications (desktop/phone/iOS/Android).
Inheritance: AbstractClientApplication
		public App()
		{
			InitializeComponent();

			AuthenticationClient = new PublicClientApplication(Constants.ApplicationID);
			MainPage = new NavigationPage(new LoginPage());
		}
        /// <summary>
        /// Get a Microsoft Graph access token using the v2.0 Endpoint.
        /// </summary>
        /// <param name="appClientId">Application client ID</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <param name="loginHint">UPN</param>
        /// <returns>An oauth2 access token.</returns>
        internal async Task <string> GetUserTokenV2Async(string appClientId, UIParent uiParent = null, string redirectUri = null, string loginHint = null)
        {
            if (_identityClient == null)
            {
                _identityClient = new MSAL.PublicClientApplication(appClientId);
            }

            if (!string.IsNullOrEmpty(redirectUri))
            {
                _identityClient.RedirectUri = redirectUri;
            }

            var upnLoginHint = string.Empty;

            if (!string.IsNullOrEmpty(loginHint))
            {
                upnLoginHint = loginHint;
            }

            MSAL.AuthenticationResult authenticationResult = null;

            var user = _identityClient.Users.FirstOrDefault();

            authenticationResult = user != null ? await _identityClient.AcquireTokenSilentAsync(DelegatedPermissionScopes, user) : await _identityClient.AcquireTokenAsync(DelegatedPermissionScopes, upnLoginHint, uiParent);

            return(authenticationResult?.AccessToken);
        }
        protected override void ProcessRecord()
        {
            PublicClientApplication clientApplication =
                new PublicClientApplication(MSALPnPPowerShellClientId);

            // Acquire an access token for the given scope
            var authenticationResult = clientApplication.AcquireTokenAsync(Scopes).GetAwaiter().GetResult();

            // Get back the Access Token and the Refresh Token
            PnPAzureADConnection.AuthenticationResult = authenticationResult;
        }
        public async Task<string> GetTokenSilentAsync(IPlatformParameters parameters)
        {
            try
            {
                app = new PublicClientApplication("https://login.windows.net/common", "CLIENT_ID");
                var result = await app.AcquireTokenSilentAsync(Sts.ValidScope, Sts.ValidUserName);

                return result.Token;
            }
            catch (Exception ex)
            {
                string msg = ex.Message + "\n" + ex.StackTrace;

                return msg;
            }
        }
        public void ConstructorsTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            Assert.IsNotNull(app);
            Assert.AreEqual("https://login.microsoftonline.com/common/", app.Authority);
            Assert.AreEqual(TestConstants.DefaultClientId, app.ClientId);
            Assert.AreEqual("urn:ietf:wg:oauth:2.0:oob", app.RedirectUri);
            Assert.IsTrue(app.ValidateAuthority);

            app = new PublicClientApplication(TestConstants.DefaultAuthorityGuestTenant, TestConstants.DefaultClientId);
            Assert.IsNotNull(app);
            Assert.AreEqual(TestConstants.DefaultAuthorityGuestTenant, app.Authority);
            Assert.AreEqual(TestConstants.DefaultClientId, app.ClientId);
            Assert.AreEqual("urn:ietf:wg:oauth:2.0:oob", app.RedirectUri);
            Assert.IsTrue(app.ValidateAuthority);
        }
 public static async Task<AuthenticationResult> GetTokenSilentAsync(User user)
 {
     TokenBroker brkr = new TokenBroker();
     PublicClientApplication app =
         new PublicClientApplication("7c7a2f70-caef-45c8-9a6c-091633501de4");
     try
     {
         return await app.AcquireTokenSilentAsync(brkr.Sts.ValidScope);
     }
     catch (Exception ex)
     {
         string msg = ex.Message + "\n" + ex.StackTrace;
         Console.WriteLine(msg);
         return await app.AcquireTokenAsync(brkr.Sts.ValidScope, user.DisplayableId, UiOptions.ActAsCurrentUser, null);
     }
     
 }
        public void GetUsersTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            IEnumerable<User> users = app.Users;
            Assert.IsNotNull(users);
            Assert.IsFalse(users.Any());
            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(1, users.Count());
            foreach (var user in users)
            {
                Assert.AreEqual(TestConstants.DefaultClientId, user.ClientId);
                Assert.IsNotNull(user.TokenCache);
            }

            // another cache entry for different home object id. user count should be 2.
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId+"more",
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3600)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.ScopeSet = TestConstants.DefaultScope;

            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            app.UserTokenCache.tokenCacheDictionary[key] = ex;

            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(2, users.Count());
            foreach (var user in users)
            {
                Assert.AreEqual(TestConstants.DefaultClientId, user.ClientId);
                Assert.IsNotNull(user.TokenCache);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Get a Microsoft Graph access token from Azure AD V2.
        /// </summary>
        /// <param name="scopes">Scopes represent various permission levels that an app can request from a user</param>
        /// <returns>An oauth2 access token.</returns>
        internal static async Task <string> AuthenticateMsalUserAsync(string[] scopes)
        {
            if (_identityClient == null)
            {
                _identityClient = new MSAL.PublicClientApplication(_appClientId);
            }

            MSAL.AuthenticationResult authenticationResult = null;
            try
            {
                authenticationResult = await _identityClient.AcquireTokenSilentAsync(scopes, _identityClient.Users.First());
            }
            catch (Exception)
            {
                authenticationResult = await _identityClient.AcquireTokenAsync(scopes);
            }

            return(authenticationResult.AccessToken);
        }
Esempio n. 9
0
        /// <summary>
        /// Get a Microsoft Graph access token using the v2.0 Endpoint.
        /// </summary>
        /// <param name="appClientId">Application client ID</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <param name="loginHint">UPN</param>
        /// <returns>An oauth2 access token.</returns>
        public async Task <string> GetUserTokenV2Async(string appClientId, UIParent uiParent = null, string redirectUri = null, string loginHint = null)
        {
            if (_identityClient == null)
            {
                _identityClient = new MSAL.PublicClientApplication(appClientId);
            }

            if (!string.IsNullOrEmpty(redirectUri))
            {
                _identityClient.RedirectUri = redirectUri;
            }

            var upnLoginHint = string.Empty;

            if (!string.IsNullOrEmpty(loginHint))
            {
                upnLoginHint = loginHint;
            }

            MSAL.AuthenticationResult authenticationResult = null;

            try
            {
                IAccount account = (await _identityClient.GetAccountsAsync()).FirstOrDefault();
                authenticationResult = await _identityClient.AcquireTokenSilentAsync(DelegatedPermissionScopes, account);
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    authenticationResult = await _identityClient.AcquireTokenAsync(DelegatedPermissionScopes, upnLoginHint, uiParent);
                }
                catch (MsalException)
                {
                    throw;
                }
            }

            return(authenticationResult?.AccessToken);
        }
 public AuthenticationHelperMSAL(IPlatformParameters platformParameters)
 {
     _identityClient = new PublicClientApplication(ClientId);
     _identityClient.PlatformParameters = platformParameters;
 }
Esempio n. 11
0
 public IdentityService(IConfiguration configuration)
 {
     _configuration = configuration;
     _pca = new PublicClientApplication(_configuration.ApplicationId);
 }
        public void AcquireTokenSilentForceRefreshTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();

            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId, TestConstants.DefaultScope.Union(TestConstants.ScopeForAnotherResource).ToArray())
            };

            Task<AuthenticationResult> task = app.AcquireTokenSilentAsync(TestConstants.DefaultScope.ToArray(), TestConstants.DefaultUniqueId, app.Authority, null, true);
            AuthenticationResult result = task.Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.User.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.User.UniqueId);
            Assert.AreEqual(TestConstants.DefaultScope.Union(TestConstants.ScopeForAnotherResource).ToArray().AsSingleString(), result.Scope.AsSingleString());
        }
        public void AcquireTokenSilentServiceErrorTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();
            mockHandler.Method = HttpMethod.Post;
            mockHandler.ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage();
            HttpMessageHandlerFactory.MockHandler = mockHandler;
                try
                {
                    Task<AuthenticationResult> task =app.AcquireTokenSilentAsync(TestConstants.ScopeForAnotherResource.ToArray(), TestConstants.DefaultUniqueId);
                    AuthenticationResult result = task.Result;
                    Assert.Fail("AdalSilentTokenAcquisitionException was expected");
                }
                catch (AggregateException ex)
                {
                    Assert.IsNotNull(ex.InnerException);

                    Assert.IsTrue(ex.InnerException is MsalSilentTokenAcquisitionException);
                    var msalExc = (MsalSilentTokenAcquisitionException) ex.InnerException;
                    Assert.AreEqual(MsalError.FailedToAcquireTokenSilently, msalExc.ErrorCode);
                    Assert.IsNotNull(msalExc.InnerException, "MsalSilentTokenAcquisitionException inner exception is null");
                    Assert.AreEqual(((MsalException)msalExc.InnerException).ErrorCode, "invalid_grant");
                }
            }
        public void GetUsersAndSignThemOutTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();

            foreach (var user in app.Users)
            {
                user.SignOut();
            }
            
            Assert.AreEqual(0, app.UserTokenCache.Count);
        }
        public void AcquireTokenSilentCacheOnlyLookupTest()
        {
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            app.UserTokenCache = TokenCacheHelper.CreateCacheWithItems();
            app.UserTokenCache.tokenCacheDictionary.Remove(new TokenCacheKey(TestConstants.DefaultAuthorityGuestTenant,
                TestConstants.ScopeForAnotherResource, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId + "more", TestConstants.DefaultDisplayableId,
                TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy));
            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.Forbidden) //fail the request if it goes to http client due to any error
            };

            Task<AuthenticationResult> task = app.AcquireTokenSilentAsync(TestConstants.DefaultScope.ToArray());
            AuthenticationResult result = task.Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, result.User.DisplayableId);
            Assert.AreEqual(TestConstants.DefaultUniqueId, result.User.UniqueId);
            Assert.AreEqual(TestConstants.DefaultScope.AsSingleString(), result.Scope.AsSingleString());
        }
		public AuthenticationProvider()
		{
			ActiveDirectoryB2CAuthenticationClient = new PublicClientApplication(Constants.ApplicationID);
		}
Esempio n. 17
0
 /// <summary>
 /// .NET specific method for intergrated auth. To support Xamarin, we would need to move these to platform specific libraries.
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="authority"></param>
 /// <param name="policy"></param>
 /// <param name="app"></param>
 /// <returns></returns>
 public static async Task <AuthenticationResult> AcquireTokenWithIntegratedAuthAsync(this PublicClientApplication app, string[] scope, string authority, string policy)
 {
     return
         (await
          app.AcquireTokenWithIntegratedAuthInternalAsync(scope, authority, policy).ConfigureAwait(false));
 }
        public static async Task<string> GetTokenIntegratedAuthAsync(Sts Sts)
        {
            try
            {
                PublicClientApplication app = new PublicClientApplication(Sts.Authority, "7c7a2f70-caef-45c8-9a6c-091633501de4");
                var result = await app.AcquireTokenWithIntegratedAuthAsync(Sts.ValidScope);
                return result.Token;
            }
            catch (Exception ex)
            {
                string msg = ex.Message + "\n" + ex.StackTrace;

                return msg;
            }
        }
        public static async Task<AuthenticationResult> GetTokenInteractiveAsync()
        {
            try
            {
                TokenBroker brkr = new TokenBroker();
                PublicClientApplication app =
                    new PublicClientApplication("7c7a2f70-caef-45c8-9a6c-091633501de4");
                await app.AcquireTokenAsync(brkr.Sts.ValidScope);

                return await app.AcquireTokenAsync(brkr.Sts.ValidScope);
            }
            catch (Exception ex)
            {
                string msg = ex.Message + "\n" + ex.StackTrace;
                Console.WriteLine(msg);
            }

            return null;
        }
        public void AcquireTokenIdTokenOnlyResponseTest()
        {
            MockWebUI webUi = new MockWebUI();
            webUi.HeadersToValidate = new Dictionary<string, string>();
            webUi.MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");

            IWebUIFactory mockFactory = Substitute.For<IWebUIFactory>();
            mockFactory.CreateAuthenticationDialog(Arg.Any<IPlatformParameters>()).Returns(webUi);
            PlatformPlugin.WebUIFactory = mockFactory;
            
            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessIdTokenResponseMessage()
            };

            // this is a flow where we pass client id as a scope
            PublicClientApplication app = new PublicClientApplication(TestConstants.DefaultClientId);
            Task<AuthenticationResult> task = app.AcquireTokenAsync(new string[] {TestConstants.DefaultClientId});
            AuthenticationResult result = task.Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(result.Token, result.IdToken);
            Assert.AreEqual(1, app.UserTokenCache.Count);
            foreach (var item in app.UserTokenCache.ReadItems(TestConstants.DefaultClientId))
            {
                Assert.AreEqual(1, item.Scope.Count);
                Assert.AreEqual(TestConstants.DefaultClientId, item.Scope.AsSingleString());
            }

            //call AcquireTokenSilent to make sure we get same token back and no call goes over network
            HttpMessageHandlerFactory.MockHandler = new MockHttpMessageHandler()
            {
                Method = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
            };

            task = app.AcquireTokenSilentAsync(new string[] { TestConstants.DefaultClientId });

            AuthenticationResult result1 = task.Result;
            Assert.IsNotNull(result1);
            Assert.AreEqual(result1.Token, result1.IdToken);
            Assert.AreEqual(result.Token, result1.Token);
            Assert.AreEqual(result.IdToken, result1.IdToken);
            Assert.AreEqual(1, app.UserTokenCache.Count);
            foreach (var item in app.UserTokenCache.ReadItems(TestConstants.DefaultClientId))
            {
                Assert.AreEqual(1, item.Scope.Count);
                Assert.AreEqual(TestConstants.DefaultClientId, item.Scope.AsSingleString());
            }
        }