AcquireTokenAsync() public method

public AcquireTokenAsync ( string scope ) : Task
scope string
return Task
        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;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Get Token for User.
        /// </summary>
        /// <returns>Token for user.</returns>
        public static async Task <string> GetTokenForUserAsync()
        {
            AuthenticationResult   authResult;
            IEnumerable <IAccount> accounts = await IdentityClientApp.GetAccountsAsync();

            IAccount firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, firstAccount);
            }
            catch (MsalUiRequiredException)
            {
                authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);
            }
            return(authResult.AccessToken);
        }
 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);
     }
     
 }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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);
        }
        /// <summary>
        /// Get Token for User.
        /// </summary>
        /// <returns>Token for user.</returns>
        public static async Task <string> GetTokenForUserAsync()
        {
            AuthenticationResult authResult = null;

            try
            {
                IEnumerable <IAccount> accounts = await IdentityClientApp.GetAccountsAsync();

                IAccount firstAccount = accounts.FirstOrDefault();

                authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, firstAccount);

                return(authResult.AccessToken);
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync.
                //This indicates you need to call AcquireTokenAsync to acquire a token

                authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);

                return(authResult.AccessToken);
            }
        }
        /// <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);
        }
        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;
        }
Exemplo n.º 9
0
        static async Task UseMSGraphSDKWithMSAL()
        {
            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async(requestMessage) =>
            {
                // Configure the permissions
                String[] scopes =
                {
                    "User.Read",
                    "User.ReadBasic.All",
                    "Mail.Send",
                    "Mail.Read",
                    "Group.ReadWrite.All",
                    "Sites.Read.All",
                    "Directory.AccessAsUser.All",
                    "Files.ReadWrite",
                };

                // Acquire an access token for the given scope.
                MSAL_clientApplication.RedirectUri = "urn:ietf:wg:oauth:2.0:oob";
                var authenticationResult           = await MSAL_clientApplication.AcquireTokenAsync(scopes);

                // Get back the access token.
                MSAL_AccessToken = authenticationResult.Token;

                // Configure the HTTP bearer Authorization Header
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", MSAL_AccessToken);
            }));

            await ShowMyDisplayName(graphClient);

            await SelectUsers(graphClient);

            await FilterUsers(graphClient);

            await FilterAndOrderUsers(graphClient);

            await PartitionInboxMessages(graphClient);

            await ExpandFiles(graphClient);

            await BrowseUsersPages(graphClient);

            await CreateUnifiedGroup(graphClient);

            await SendMail(graphClient, "*****@*****.**", "Paolo Pialorsi");

            await ListUnifiedGroups(graphClient);

            await GetGroupFiles(graphClient);

            await SearchGroupFiles(graphClient, "sample");

            await GetGroupConversations(graphClient);

            await GetGroupEvents(graphClient);

            await AddGroupConversationThread(graphClient);

            await AddGroupEvent(graphClient);

            await ManageCurrentUserPicture(graphClient);

            await RetrieveCurrentUserManagerAndReports(graphClient);

            await UploadFileToOneDriveForBusiness(graphClient);

            await SearchForFilesInOneDriveForBusiness(graphClient, "contract");
        }
        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());
            }
        }