示例#1
0
        private static async Task <IAuthenticationProvider> GetAuthProvider()
        {
            var app = ConfidentialClientApplicationBuilder.Create(clientId)
                      .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
                      .WithClientSecret(clientSecret)
                      .Build();

            //Change this to scope of the requested service.
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult result = null;

            //try
            //{
            result = await app.AcquireTokenForClient(scopes).ExecuteAsync();

            //AuthenticationContext authenticationContext = new AuthenticationContext(authority);
            //ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

            //result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
            //AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResource, clientCred);

            //var token = authenticationResult.AccessToken;
            var token = result.AccessToken;

            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString());
                return(Task.FromResult(0));
            });

            return(delegateAuthProvider);
            //}
        }
示例#2
0
        /*Backup
         *       public async Task AuthenticateRequestAsync(HttpRequestMessage request)
         * {
         *  var token = GetToken();
         *  request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
         *  await Task.CompletedTask;
         * }
         */

        /// <summary>
        /// Acquire Token
        /// </summary>
        public async Task <string> GetTokenAsync()
        {
            Microsoft.Identity.Client.AuthenticationResult authResult = null;
            //authResult.
            //authResult = ;
            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);
        }
示例#4
0
        public JsonResult Get(string id)
        {
            string emailAddress = id;
            string result;

            try
            {
                ConfidentialClientApplication cl = new ConfidentialClientApplication(
                    AppConstants.ClientId,
                    String.Format(AppConstants.GraphV2Uri, AppConstants.TenentName),
                    AppConstants.RedirectUrl,
                    new Microsoft.Identity.Client.ClientCredential(AppConstants.ClientSecret),
                    new TokenCache(),
                    new TokenCache());
                Microsoft.Identity.Client.AuthenticationResult authResult = cl.AcquireTokenForClientAsync(new string[] { AppConstants.ApplicationDefaultScope }).Result;
                string bearerToken = AppConstants.Bearer + " " + authResult.AccessToken.ToString();
                var    client      = new HttpClient();
                var    queryString = HttpUtility.ParseQueryString(string.Empty);
                var    userUpn     = emailAddress.Replace('@', '_') + AppConstants.ExtensionAttachedForAd + AppConstants.TenentName;
                var    uri         = string.Format(AppConstants.GraphApiV1Url, HttpUtility.UrlEncode(userUpn));
                client.DefaultRequestHeaders.Add(AppConstants.AuthorizatioHeader, bearerToken);
                var response = client.GetAsync(uri).GetAwaiter().GetResult();
                if (response.StatusCode == HttpStatusCode.OK && response.Content != null)
                {
                    var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    var jsonResponse   = Newtonsoft.Json.JsonConvert.DeserializeObject <JObject>(responseString)["value"];
                    return(this.Json(jsonResponse));
                }
            }
            catch (Exception ex)
            {
                return(this.Json(new object()));
            }
            return(this.Json(new object()));
        }
示例#5
0
        /// <summary>
        /// Call AcquireTokenAsync - to acquire a token requiring user to sign-in
        /// </summary>
        private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Identity.Client.AuthenticationResult authResult = null;
            var app = App.PublicClientApp;

            ////ResultText.Text = string.Empty;
            ////TokenInfoText.Text = string.Empty;
            ////var p = new PlatformParameters(PromptBehavior.Always);
            ////Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(ConfigurationSettings.AppSettings["authority"]);
            ////IPlatformParameters parameters;
            ////var authenticationResult = authContext.AcquireTokenAsync(
            ////    ConfigurationSettings.AppSettings["ida:ResourceId"],
            ////    ConfigurationSettings.AppSettings["clientId"],
            ////    new Uri(ConfigurationSettings.AppSettings["ida:RedirectUri"]),
            ////    p ).GetAwaiter().GetResult();
            if (this.isRest.IsChecked.Value)
            {
                scopes = this.scopesRest;
            }
            else
            {
                scopes = this.scopesGraph;
            }

            try
            {
                authResult = await app.AcquireTokenAsync(scopes, app.Users.FirstOrDefault());
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync.
                // This indicates you need to call AcquireTokenAsync to acquire a token
                System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    authResult = await app.AcquireTokenAsync(scopes);
                }
                catch (MsalException msalex)
                {
                    ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
                }
            }
            catch (Exception ex)
            {
                ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
                return;
            }

            if (authResult != null)
            {
                ResultText.Text = await GetHttpContentWithToken(graphAPIEndpoint, authResult.AccessToken);

                DisplayBasicTokenInfo(authResult);
                this.SignOutButton.Visibility = Visibility.Visible;
            }
        }
        /// <summary>
        /// We obtain access token for Microsoft Graph with the scope "group.read.all". Since this access token was not obtained during the initial sign in process
        /// (OnAuthorizationCodeReceived), the user will be prompted to consent again.
        /// </summary>
        /// <returns></returns>
        private async Task <string> GetGraphAccessToken(string[] scopes)
        {
            IConfidentialClientApplication cc = MsalAppBuilder.BuildConfidentialClientApplication();
            IAccount userAccount = await cc.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());

            Microsoft.Identity.Client.AuthenticationResult result = await cc.AcquireTokenSilent(scopes, userAccount).ExecuteAsync();

            return(result.AccessToken);
        }
示例#7
0
 /// <summary>
 /// Display basic information contained in the token
 /// </summary>
 private void DisplayBasicTokenInfo(Microsoft.Identity.Client.AuthenticationResult authResult)
 {
     TokenInfoText.Text = "";
     if (authResult != null)
     {
         TokenInfoText.Text += $"Username: {authResult.Account.Username}" + Environment.NewLine;
         TokenInfoText.Text += $"Token Expires: {authResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine;
     }
 }
示例#8
0
        public async Task <IActionResult> PowerBI(PowerBIModel data)
        {
            List <ValidationResult> errors = new List <ValidationResult>();

            try
            {
                ValidatePowerBIConfiguration(errors, data);

                if (!errors.Any())
                {
                    IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                                               .Create(data.ClientId)
                                                               .WithClientSecret(data.AppSecret)
                                                               .WithAuthority($"{data.Authority}{data.TenantId}")
                                                               .Build();
                    List <string> scopes = new List <string>
                    {
                        data.Scope,
                    };

                    Microsoft.Identity.Client.AuthenticationResult authenticationResult = await clientApp.AcquireTokenForClient(scopes).ExecuteAsync();

                    if (authenticationResult is null)
                    {
                        errors.Add(new ValidationResult("Unable to authenticate the Power BI client"));
                    }
                    if (!errors.Any())
                    {
                        TokenCredentials tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

                        // 3. Get embedded report info
                        var client = new PowerBIClient(new Uri(data.APIBaseURL), tokenCredentials);

                        Reports reports = client.Reports.GetReports(Guid.Parse(data.WorkSpaceId));

                        ViewBag.Reports = reports;
                    }
                }
            }
            catch (HttpOperationException ex)
            {
                errors.Add(new ValidationResult(ex.Message));
            }
            catch (Exception e)
            {
                errors.Add(new ValidationResult(e.Message));
            }

            errors.ForEach(_ =>
            {
                ModelState.AddModelError(string.Empty, _.ErrorMessage);
            });

            return(View(data));
        }
示例#9
0
        public async Task <Microsoft.Identity.Client.AuthenticationResult> GetServiceTokenbyCertificate(string resource)
        {
            // Even if this is a console application here, a daemon application is a confidential client application
            IConfidentialClientApplication app;

            X509Certificate2 certificate;

            // If there is a name on the certificate we use the machine store an look up for that certificate
            // The current user must have access to the certificate keys
            var certName = _configuration["AppId:certificate:name"];

            if (!String.IsNullOrEmpty(certName))
            {
                _logger.LogInformation($"Using machine store certifcate.");
                certificate = ReadCertificate(certName);
            }
            else // otherwhise we get the cert from a key vault
            {
                _logger.LogInformation($"Using Azure Key Vault");
                var secret = await GetSecretFromKV();

                certificate = new X509Certificate2(Convert.FromBase64String(secret));
            }

            string authority = _configuration["AppId:authority"];

            app = ConfidentialClientApplicationBuilder.Create(_configuration["AppId:id"])
                  .WithCertificate(certificate)
                  .WithAuthority(new Uri(authority))
                  .Build();

            // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
            // application permissions need to be set statically (in the portal or by PowerShell), and then granted by
            // a tenant administrator
            string[] scopes = new string[] { $"{resource}/.default" };

            Microsoft.Identity.Client.AuthenticationResult result = null;
            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

                _logger.LogInformation("Token acquired");
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                _logger.LogError("Scope provided is not supported");
            }

            return(result);
        }
示例#10
0
        private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Identity.Client.AuthenticationResult authResult = null;
            var app = App.PublicClientApp;

            ResultText.Text    = string.Empty;
            TokenInfoText.Text = string.Empty;

            var accounts = await app.GetAccountsAsync();

            var firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await app.AcquireTokenSilent(scopes, firstAccount)
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilent.
                // This indicates you need to call AcquireTokenInteractive to acquire a token
                System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    authResult = await app.AcquireTokenInteractive(scopes)
                                 .WithAccount(firstAccount)
                                 .WithSystemWebViewOptions(new SystemWebViewOptions()
                    {
                        OpenBrowserAsync = SystemWebViewOptions.OpenWithChromeEdgeBrowserAsync
                    })
                                 .WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount)
                                 .ExecuteAsync();
                }
                catch (MsalException msalex)
                {
                    ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
                }
            }
            catch (Exception ex)
            {
                ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
                return;
            }

            if (authResult != null)
            {
                ResultText.Text = await GetHttpContentWithToken(graphAPIEndpoint, authResult.AccessToken);

                DisplayBasicTokenInfo(authResult);
                this.SignOutButton.Visibility = Visibility.Visible;
            }
        }
示例#11
0
        public static async Task <AuthenticationResult> ExecuteAsync <T>(this AbstractAcquireTokenParameterBuilder <T> builder, bool async, CancellationToken cancellationToken)
            where T : AbstractAcquireTokenParameterBuilder <T>
        {
            Microsoft.Identity.Client.AuthenticationResult result = async
                ? await builder.ExecuteAsync(cancellationToken).ConfigureAwait(false)
#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
                : builder.ExecuteAsync(cancellationToken).GetAwaiter().GetResult();

#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.

            return(result);
        }
示例#12
0
        public static AuthResult FromMSALAuthenticationResult(Microsoft.Identity.Client.AuthenticationResult authResult, Microsoft.Identity.Client.TokenCache tokenCache)
        {
            var result = new AuthResult
            {
                AccessToken       = authResult.AccessToken,
                UserName          = $"{authResult.User.Name}",
                UserUniqueId      = authResult.User.Identifier,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache        = tokenCache.Serialize()
            };

            return(result);
        }
        /// <summary>
        /// Sign out of all active accounts associated with this app.
        /// </summary>
        public async Task SignOutAsync()
        {
            do
            {
                var accountsLoaded = await publicClientApplication.GetAccountsAsync();

                accounts = accountsLoaded.ToList();
                await publicClientApplication.RemoveAsync(accounts.FirstOrDefault());
            } while (accounts.Any());

            authResult = null;
            accounts   = null;
        }
        /// ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ///
        ///
        /// GetAuthGatewayUserLoginSavedCredential Method (Saved Credential)
        ///
        public async Task <Microsoft.Identity.Client.AuthenticationResult> GetAuthGatewayUserLoginSavedCredential()
        {
            Microsoft.Identity.Client.AuthenticationResult authResult = null;
            AuthorityURI = defaultAuthorityURI + AzureTenantID;

            try
            {
                Console.WriteLine("        Authority URI: " + AuthorityURI);
                Console.WriteLine("        Resource URI: " + PowerBIResourceURI);
                Console.WriteLine("        Application ID: " + GatewayMgmtApplicationID);
                Console.WriteLine("        Access Scope: " + PowerBIAccessScope);
                Console.WriteLine("        Username: "******"", Password).SecurePassword;
                var          accessTokenRequest = publicClient.AcquireTokenByUsernamePassword(scopes, UserName, PasswordSecure);

                authResult = await accessTokenRequest.ExecuteAsync();
            }
            catch (AggregateException ex)
            {
                MsalServiceException ex1 = (MsalServiceException)ex.GetBaseException();

                Console.WriteLine("   - Error acquiring token with ApplicationID/Secret (User/Pass) [GatewayMgmt].  ");
                Console.WriteLine("     Usually this is due to an invalid password");
                Console.WriteLine("");
                Console.WriteLine("     Details: " + ex1.StatusCode + ": " + ex1.ResponseBody);
            }
            catch (Exception ex)
            {
                Console.WriteLine("   - Error acquiring token with ApplicationID/Secret (User/pass) [GatewayMgmt].  ");
                Console.WriteLine("     Usually this is due to an invalid password");
                Console.WriteLine("");
                Console.WriteLine("     Details: " + ex.ToString());
            }

            return(authResult);
        }
        /// ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ///
        ///
        /// GetAuthUserLoginSavedSPN Method (Saved SPN Auth)
        ///
        public async Task <Microsoft.Identity.Client.AuthenticationResult> GetAuthUserLoginSavedSPN()
        {
            Microsoft.Identity.Client.AuthenticationResult authResult = null;

            try
            {
                Console.WriteLine("        Authority URI: " + MSALAuthorityURI);
                Console.WriteLine("        Resource URI: " + PowerBIResourceURI);
                Console.WriteLine("        Application ID: " + ApplicationID);
                Console.WriteLine("        Access Scope: " + PowerBIAccessScope);
                //Console.WriteLine("        Client Secret: " + ClientSecret);

                // Build the access scope list
                List <string> scopes = new List <string>();
                scopes.Add(PowerBIAccessScope);

                // Build the authentication request client
                var confidentialClient = ConfidentialClientApplicationBuilder
                                         .Create(ApplicationID)
                                         .WithClientSecret(ClientSecret)
                                         .WithAuthority(new Uri(MSALAuthorityURI))
                                         .WithRedirectUri(PowerBIRedirectURI)
                                         .Build();

                // Request an access token with the request client and scope
                var accessTokenRequest = confidentialClient.AcquireTokenForClient(scopes);

                authResult = await accessTokenRequest.ExecuteAsync();
            }
            catch (AggregateException ex)
            {
                MsalServiceException ex1 = (MsalServiceException)ex.GetBaseException();

                Console.WriteLine("   - Error acquiring token with ApplicationID/Secret (SPN).");
                Console.WriteLine("     Usually this is due to an invalid Application (client) ID or Client Secret");
                Console.WriteLine("");
                Console.WriteLine("     Details: " + ex1.StatusCode + ": " + ex1.ResponseBody);
            }
            catch (Exception ex)
            {
                Console.WriteLine("   - Error acquiring token with ApplicationID/Secret (SPN).");
                Console.WriteLine("     Usually this is due to an invalid Application (client) ID or Client Secret");
                Console.WriteLine("");
                Console.WriteLine("     Details: " + ex.Message.ToString());
            }

            return(authResult);
        }
        private async void AcquireTokenIWA_ClickAsync(object sender, RoutedEventArgs e)
        {
            AuthenticationResult result = null;

            try
            {
                result = await _pca.AcquireTokenByIntegratedWindowsAuthAsync(Scopes).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await DisplayErrorAsync(ex).ConfigureAwait(false);

                return;
            }

            await DisplayResultAsync(result).ConfigureAwait(false);
        }
示例#17
0
        public static async Task <string> FetchTokenConfidentalAsync(string[] scopes)
        {
            try
            {
                Microsoft.Identity.Client.ConfidentialClientApplication cc = new Microsoft.Identity.Client.ConfidentialClientApplication(PBIConfig.ClientId, PBIConfig.RedirectUrl, new Microsoft.Identity.Client.ClientCredential(PBIConfig.ClientSecret), null, null);
                //            var accounts = await cc.GetAccountsAsync();
                //            Microsoft.Identity.Client.AuthenticationResult result = await cc.AcquireTokenSilentAsync(scopes, accounts.First());
                Microsoft.Identity.Client.AuthenticationResult result = await cc.AcquireTokenForClientAsync(scopes);

                return(result.AccessToken);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(null);
        }
示例#18
0
        public static async Task <string> GetAuthTokenByUserCredentialsSilentAsync(Settings input)
        {
            var apiScopes = GetApiScopes(input);

            if (string.IsNullOrWhiteSpace(input.Tenant) || string.IsNullOrWhiteSpace(input.ClientId) || string.IsNullOrWhiteSpace(input.UserId) || string.IsNullOrWhiteSpace(input.Password) || apiScopes?.Any() != true)
            {
                throw new ArgumentException($"To use the User-credentials silent-flow, please provide valid Tenant, ClientId, UserId, Password, ApiScopes in '{input.AppSettingsFile}'");
            }

            ColorConsole.WriteLine("Acquiring token for ", input.UserId.Green(), " ...");
            var app      = PublicClientApplicationBuilder.Create(input.ClientId).WithAuthority(input.Authority).Build();
            var accounts = await app.GetAccountsAsync().ConfigureAwait(continueOnCapturedContext: false);

            AuthenticationResult result = null;

            if (accounts?.Any() == true)
            {
                result = await app.AcquireTokenSilent(apiScopes, accounts.FirstOrDefault()).ExecuteAsync();
            }
            else
            {
                try
                {
                    var securePassword = new SecureString();
                    var pwd            = input.Password;
                    foreach (char c in pwd)
                    {
                        securePassword.AppendChar(c);
                    }

                    result = await app.AcquireTokenByUsernamePassword(apiScopes, input.UserId, securePassword).ExecuteAsync();
                }
                catch (MsalException mex)
                {
                    ColorConsole.WriteLine(mex.Message.White().OnRed());
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteLine(ex.Message.White().OnRed());
                }
            }

            return(result.AccessToken);
        }
        /// <summary>
        ///     Default constructor.
        /// </summary>
        internal TokenCacheItem(TokenCacheKey key, AuthenticationResult result)
        {
            this.Authority = key.Authority;
            this.Scope = key.Scope;
            this.ClientId = key.ClientId;
            this.UniqueId = key.UniqueId;
            this.DisplayableId = key.DisplayableId;
            this.HomeObjectId = key.HomeObjectId;
            this.TenantId = result.TenantId;
            this.ExpiresOn = result.ExpiresOn;
            this.Token = result.Token;
            this.User = result.User;
            this.Policy = key.Policy;

            if (result.User!= null)
            {
                this.Name = result.User.Name;
            }
        }
示例#20
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);
        }
        public async Task <bool> SignInAsync(object parentWindow, string platform)
        {
            await RefreshAccounts();

            try
            {
                IAccount firstAccount = accounts.FirstOrDefault();
                authResult = await publicClientApplication
                             .AcquireTokenSilent(Scopes, firstAccount)
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                // Open a browser window, when token doesn't exist for the user in that device

                // System browser for android, Embedded webview for iOS
                bool isEmbedded = platform?.ToLower() == "android" ? false : true;

                authResult = await publicClientApplication
                             .AcquireTokenInteractive(Scopes)
                             .WithExtraScopesToConsent(ExtraScopes)
                             .WithParentActivityOrWindow(parentWindow)
                             .WithUseEmbeddedWebView(isEmbedded)
                             .ExecuteAsync();

                await RefreshAccounts();
            }

            await RequestTokenAsync("https://graph.microsoft.com/.default"); //Get the token for Graph resource.

            var graphUserData = await GraphUserDataService.LoadFromGraphApi("bearer", User.ACCESS_TOKEN);

            User.EMP_ID         = graphUserData?.EmployeeID;
            User.EMAIL          = graphUserData?.Email;
            User.COUNTRY        = graphUserData?.Country;
            User.USER_NAME      = graphUserData?.OnPremisesSamAccountName?.ToLower();
            User.USER_FULL_NAME = graphUserData?.DisplayName;
            User.DISPLAY_NAME   = "Welcome, " + graphUserData?.GivenName;

            User.ACCESS_TOKEN = authResult?.AccessToken; // Reset token to your default login resource.

            return(true);
        }
        private async void AccessTokenSilentButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            var accounts = await _pca.GetAccountsAsync().ConfigureAwait(false);

            AuthenticationResult result = null;

            try
            {
                result = await _pca.AcquireTokenSilentAsync(Scopes, accounts.FirstOrDefault()).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await DisplayErrorAsync(ex).ConfigureAwait(false);

                return;
            }

            await DisplayResultAsync(result).ConfigureAwait(false);
        }
示例#23
0
        static string GetAdsAuthToken(string appId, string appKey, string adsGraphRootUrl)
        {
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult result = null;

            try
            {
                IConfidentialClientApplication app;
                app = ConfidentialClientApplicationBuilder.Create(appId)
                      .WithClientSecret(appKey)
                      .WithAuthority(new Uri("https://login.microsoftonline.com/4ae48b41-0137-4599-8661-fc641fe77bea/oauth2/token"))
                      .Build();


                result = app.AcquireTokenForClient(scopes)
                         .ExecuteAsync().Result;

                if (result != null)
                {
                    return(result.AccessToken);
                }
            }
            catch (MsalUiRequiredException ex)
            {
                // The application doesn't have sufficient permissions.
                // - Did you declare enough app permissions during app creation?
                // - Did the tenant admin grant permissions to the application?
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be in the form "https://resourceurl/.default"
                // Mitigation: Change the scope to be as expected.
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }

            return("");
        }
        private async void AccessTokenButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            AuthenticationResult result = null;

            try
            {
                var users = await _pca.GetAccountsAsync().ConfigureAwait(false);

                var user = users.FirstOrDefault();

                result = await _pca.AcquireTokenAsync(Scopes, user, UIBehavior.ForceLogin, "").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await DisplayErrorAsync(ex).ConfigureAwait(false);

                return;
            }

            await DisplayResultAsync(result).ConfigureAwait(false);
        }
示例#25
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);
        }
        private async void AccessTokenButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            AuthenticationResult result = null;

            try
            {
                IEnumerable <IAccount> users = await _pca.GetAccountsAsync().ConfigureAwait(false);

                IAccount user = users.FirstOrDefault();

                result = await _pca.AcquireTokenInteractive(s_scopes)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await DisplayErrorAsync(ex).ConfigureAwait(false);

                return;
            }

            await DisplayResultAsync(result).ConfigureAwait(false);
        }
示例#27
0
        public static async Task <string> GetAuthTokenSilentAsync(AuthInfo input)
        {
            var app      = PublicClientApplicationBuilder.Create(input.ClientId).WithAuthority(input.Authority).Build();
            var accounts = await app.GetAccountsAsync().ConfigureAwait(continueOnCapturedContext: false);

            AuthenticationResult result = null;

            if (accounts?.Any() ?? false)
            {
                result = await app.AcquireTokenSilent(input.ApiScopes, accounts.FirstOrDefault()).ExecuteAsync();
            }
            else
            {
                try
                {
                    var securePassword = new SecureString();
                    var pwd            = input.Password;
                    foreach (char c in pwd)
                    {
                        securePassword.AppendChar(c);
                    }
                    result = await app.AcquireTokenByUsernamePassword(input.ApiScopes, input.UserId, securePassword).ExecuteAsync();
                }
                catch (MsalException mex)
                {
                    Console.WriteLine(mex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.WriteLine($"\n{result.Account.Username}\n");
            return(result.AccessToken);
        }
示例#28
0
        private async Task <string> GetAccessToken()
        {
            var app     = GetConfidentialClientApplication();
            var scopes  = _options.Value.TargetApiScopes.Split(';');
            var account = (await app.GetAccountsAsync()).FirstOrDefault();

            Microsoft.Identity.Client.AuthenticationResult authResult = null;
            try
            {
                authResult = await app.AcquireTokenSilent(scopes, account).ExecuteAsync();

                return(authResult.AccessToken);
            }
            catch (MsalUiRequiredException ex)
            {
                string token = await HttpContext.GetTokenAsync(OidcConstants.TokenTypes.AccessToken);

                UserAssertion userAssertion = new UserAssertion(token, OidcConstants.GrantTypes.JwtBearer);

                authResult = await app.AcquireTokenOnBehalfOf(scopes, userAssertion).ExecuteAsync();

                return(authResult.AccessToken);
            }
        }
示例#29
0
        public static async Task <string> GetAccessTokenCal(ITurnContext <IMessageActivity> context, IConfiguration ConfigurationManager, IStatePropertyAccessor <UserProfileState> userState)
        {
            string accessToken = null;

            // Load the app config from web.config
            string appId       = ConfigurationManager["ida:AppId"];
            string appPassword = ConfigurationManager["ida:AppPassword"];
            string redirectUri = ConfigurationManager["ida:RedirectUri"];

            string[] scopes = ConfigurationManager["ida:AppScopes"]
                              .Replace(' ', ',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            // Get the current user's ID
            string userId = ClaimsPrincipal.Current.Claims.FirstOrDefault(x => x.Type == "iss").Value;

            userId = userId.Replace("https://login.microsoftonline.com/", "");
            userId = userId.Substring(0, userId.IndexOf("/"));
            if (!string.IsNullOrEmpty(userId))
            {
                var accessCode = await GetCurrentAccessCode(context, userState);

                var ccd = ConfidentialClientApplicationBuilder.Create(appId).WithRedirectUri(redirectUri).WithClientSecret(appPassword).Build();

                //ConfidentialClientApplication cca = new ConfidentialClientApplication(
                //    appId, redirectUri, new Microsoft.Identity.Client.ClientCredential(appPassword), null, null);

                // Call AcquireTokenSilentAsync, which will return the cached
                // access token if it has not expired. If it has expired, it will
                // handle using the refresh token to get a new one.
                Microsoft.Identity.Client.AuthenticationResult result = await ccd.AcquireTokenByAuthorizationCode(scopes, accessCode).ExecuteAsync();

                accessToken = result.AccessToken;
            }

            return(accessToken);
        }
		public LogoutPage(AuthenticationResult result)
		{
			InitializeComponent();
			authenticationResult = result;
		}
 private static bool AreAuthenticationResultsEqual(AuthenticationResult result1, AuthenticationResult result2)
 {
     return (AreStringsEqual(result1.Token, result2.Token)
             && AreStringsEqual(result1.TokenType, result2.TokenType)
             && AreStringsEqual(result1.IdToken, result2.IdToken)
             && AreStringsEqual(result1.TenantId, result2.TenantId)
             && (result1.User == null || result2.User == null ||
                 (AreStringsEqual(result1.User.DisplayableId, result2.User.DisplayableId)
                  && AreStringsEqual(result1.User.Name, result2.User.Name)
                  && AreStringsEqual(result1.User.IdentityProvider, result2.User.IdentityProvider)
                  && result1.User.UniqueId == result2.User.UniqueId)));
 }
        public void StoreToCacheUniqueScopesTest()
        {
            var tokenCache = new TokenCache();
            tokenCache.AfterAccess = null;
            tokenCache.BeforeAccess = null;
            tokenCache.BeforeWrite = null;
            tokenCache = TokenCacheHelper.CreateCacheWithItems();

            //save result with intersecting scopes
            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User =
                    new User
                    {
                        UniqueId = TestConstants.DefaultUniqueId,
                        DisplayableId = TestConstants.DefaultDisplayableId
                    },
                ScopeSet = new HashSet<string>(new string[] { "r1/scope5", "r1/scope7" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = "someRT"
            };

            tokenCache.StoreToCache(resultEx, TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultClientId,
                TestConstants.DefaultPolicy, TestConstants.DefaultRestrictToSingleUser, null);

            Assert.AreEqual(3, tokenCache.Count);
            AuthenticationResultEx resultExOut =
                tokenCache.LoadFromCache(TestConstants.DefaultAuthorityHomeTenant,
                    new HashSet<string>(new string[] {"r1/scope5"}), TestConstants.DefaultClientId,
                    null, TestConstants.DefaultPolicy, null);

            Assert.AreEqual(resultEx.RefreshToken, resultExOut.RefreshToken);
            Assert.AreEqual(resultEx.Result.Token, resultExOut.Result.Token);
            Assert.AreEqual(resultEx.Result.TokenType, resultExOut.Result.TokenType);
            Assert.AreEqual(resultEx.Result.User.UniqueId, resultExOut.Result.User.UniqueId);
            Assert.AreEqual(resultEx.Result.User.DisplayableId, resultExOut.Result.User.DisplayableId);
            Assert.AreEqual(resultEx.Result.User.HomeObjectId, resultExOut.Result.User.HomeObjectId);
        }
        private async void GetTodoList(bool isAppStarting)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (!accounts.Any())
            {
                SignInButton.Content = SignInString;
                return;
            }

            //
            // Get an access token to call the To Do service.
            //
            AuthenticationResult result = null;

            try
            {
                result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                this.Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    this.SetUserName(result.Account);
                });
            }
            catch (MsalUiRequiredException)
            {
                MessageBox.Show("Please re-sign");
                SignInButton.Content = SignInString;
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }

                Dispatcher.Invoke(() =>
                {
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                    MessageBox.Show("Unexpected error: " + message);
                });
            }

            // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do list service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "/api/todolist");

            if (response.IsSuccessStatusCode)
            {
                // Read the response and databind to the GridView to display To Do items.
                string s = await response.Content.ReadAsStringAsync();

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                List <TodoItem>      toDoArray  = serializer.Deserialize <List <TodoItem> >(s);
                Dispatcher.Invoke(() =>
                {
                    TodoList.ItemsSource = toDoArray.Select(t => new { t.Title });
                });
            }
            else
            {
                MessageBox.Show("An error occurred : " + response.ReasonPhrase);
            }

            return;
        }
        private async void SignIn(object sender = null, RoutedEventArgs args = null)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (SignInButton.Content.ToString() == ClearCacheString)
            {
                TodoList.ItemsSource = string.Empty;

                // clear the cache
                while (accounts.Any())
                {
                    LoginHint = accounts.First().Username;
                    await _app.RemoveAsync(accounts.First());

                    accounts = (await _app.GetAccountsAsync()).ToList();
                }

                // Also clear cookies from the browser control.
                SignInButton.Content = SignInString;
                UserName.Content     = Properties.Resources.UserNotSignedIn;
                return;
            }

            //}

            //
            // Get an access token to call the To Do list service.
            //
            AuthenticationResult result = null;

            try
            {
                if (String.IsNullOrEmpty(LoginHint))
                {
                    result = await _app.AcquireTokenInteractive(Scopes).ExecuteAsync().ConfigureAwait(false);
                }
                else
                {
                    result = await _app.AcquireTokenInteractive(Scopes).WithPrompt(Prompt.ForceLogin).WithLoginHint(LoginHint).ExecuteAsync().ConfigureAwait(false);
                }
                Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    this.SetUserName(result.Account);
                    GetTodoList();
                }
                                  );
            }
            catch (MsalException ex)
            {
                if (ex.ErrorCode == "access_denied")
                {
                    // The user canceled sign in, take no action.
                }
                else
                {
                    // An unexpected error occurred.
                    string message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                    }

                    MessageBox.Show(message);
                }

                Dispatcher.Invoke(() =>
                {
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                }
                                  );
            }
        }
        public void StoreToCacheNewUserRestrictToSingleUserTrueTest()
        {
            var tokenCache = new TokenCache();

            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            tokenCache.tokenCacheDictionary[key] = ex;
            
            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User =
                    new User
                    {
                        UniqueId = TestConstants.DefaultUniqueId+"more",
                        DisplayableId = TestConstants.DefaultDisplayableId
                    },
                ScopeSet = new HashSet<string>(new string[] { "r1/scope5", "r1/scope7" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = "someRT"
            };
            try
            {
                tokenCache.StoreToCache(resultEx, TestConstants.DefaultAuthorityGuestTenant, TestConstants.DefaultClientId,
                    TestConstants.DefaultPolicy, true, null);
                Assert.Fail("MsalException should be thrown here");
            }
            catch (MsalException me)
            {
                Assert.AreEqual(MsalError.InvalidCacheOperation, me.ErrorCode);
                Assert.AreEqual("Cannot add more than 1 user with a different unique id when RestrictToSingleUser is set to TRUE.", me.Message);
            }
        }
 private static void VerifyAuthenticationResultsAreNotEqual(AuthenticationResult result1,
     AuthenticationResult result2)
 {
     Assert.IsFalse(AreAuthenticationResultsEqual(result1, result2));
 }
        public void StoreToCacheClientCredentialTest()
        {
            TokenCache tokenCache = TokenCacheHelper.CreateCacheWithItems();

            var result = new AuthenticationResult("Bearer", "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User = null,
                ScopeSet = new HashSet<string>(new string[] { "r1/scope1" })
            };

            AuthenticationResultEx resultEx = new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = null
            };
        }
        internal AuthenticationResultEx CreateCacheValue(string uniqueId, string displayableId)
        {
            string refreshToken = string.Format(CultureInfo.InvariantCulture,"RefreshToken{0}", Rand.Next());
            var result = new AuthenticationResult(null, "some-access-token",
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)))
            {
                User = new User {UniqueId = uniqueId, DisplayableId = displayableId}
            };

            return new AuthenticationResultEx
            {
                Result = result,
                RefreshToken = refreshToken
            };
        }