Esempio n. 1
0
        // GET api/CallGraph
        public async Task <IEnumerable <string> > GetAsync()
        {
            List <string>        userList    = new List <string>();
            string               accessToken = null;
            AuthenticationResult result      = null;

            _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig());
            try
            {
                result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(requestedScopes).ConfigureAwait(false);

                accessToken = result.AccessToken;

                if (accessToken == null)
                {
                    // An unexpected error occurred.
                    return(null);
                }

                IEnumerable <User> users = await CallGraphApiOnBehalfOfUser(accessToken);

                userList = users.Select(x => x.UserPrincipalName).ToList();
                return(userList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        // GET: api/AccessCaApi/GetAll
        public async Task <List <string> > GetAll()
        {
            var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope");

            if (scopeClaim == null || (!scopeClaim.Value.ContainsAny("access_as_user")))
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'access_as_user' or scope claim not found"
                });
            }

            AuthenticationResult result = null;

            _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig());

            // In the case of a transient error, retry once after 1 second, then abandon.
            // Retrying is optional.  It may be better, for your application, to return an error immediately to the user and have the user initiate the retry.
            bool retry      = false;
            int  retryCount = 0;

            do
            {
                retry = false;
                try
                {
                    result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(caResourceIdScope);
                }
                catch (MsalUiRequiredException ex)
                {
                    await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync((caResourceIdScope),
                                                                                         ex, HttpContext.Current.Response);

                    throw new HttpResponseException(new HttpResponseMessage {
                        StatusCode = HttpStatusCode.Forbidden
                    });
                }
            } while ((retry == true) && (retryCount < 1));

            /*
             * You can now use this  access token to accesss our Conditional-Access protected Web API using On-behalf-of
             * Use this code below to call the downstream Web API OBO
             */
            string oboAccessToken = result.AccessToken;

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", oboAccessToken);
            List <string>       lstUsers = new List <string>();
            HttpResponseMessage response = await _httpClient.GetAsync(_TodoListDownstreamBaseAddress + "/api/CallGraph");

            if (response != null && response.StatusCode == HttpStatusCode.OK)
            {
                string content = response.Content.ReadAsStringAsync().Result;
                lstUsers = JsonConvert.DeserializeObject <List <string> >(content);

                return(lstUsers);
            }

            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}.");
        }
Esempio n. 3
0
 private void InitializeTokenAcquisitionObjects()
 {
     _tokenAcquisition = new TokenAcquisition(
         null,
         null,
         _provider.GetService <IOptions <MicrosoftIdentityOptions> >(),
         _provider.GetService <IOptions <ConfidentialClientApplicationOptions> >(),
         null,
         null,
         _provider);
 }
 private void InitializeTokenAcquisitionObjects()
 {
     _tokenAcquisition = new TokenAcquisition(
         new MsalTestTokenCacheProvider(
             _provider.GetService <IMemoryCache>(),
             _provider.GetService <IOptions <MsalMemoryTokenCacheOptions> >()),
         MockHttpContextAccessor.CreateMockHttpContextAccessor(),
         _provider.GetService <IOptionsMonitor <MergedOptions> >(),
         _provider.GetService <IHttpClientFactory>(),
         _provider.GetService <ILogger <TokenAcquisition> >(),
         _provider);
 }
Esempio n. 5
0
        /// <summary>
        /// Retrieves the Access Token for the Web API.
        /// Sets Authorization and Accept headers for the request.
        /// </summary>
        /// <returns></returns>
        private async Task PrepareAuthenticatedClientAsync()
        {
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            TokenAcquisition tokenAcquisition = new TokenAcquisition(new AuthenticationConfig());

            // Retrieves the Access Token for the Web API
            string[] scopes = new[] { ConfigurationManager.AppSettings["ida:TodoListServiceScope"] };
            var      result = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);

            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
        // GET: api/ConditionalAccess
        public async Task <string> Get()
        {
            var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope");

            if (scopeClaim == null || (!scopeClaim.Value.ContainsAny("access_as_user")))
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'access_as_user' or scope claim not found"
                });
            }

            AuthenticationResult result = null;

            _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig());

            // In the case of a transient error, retry once after 1 second, then abandon.
            // Retrying is optional.  It may be better, for your application, to return an error immediately to the user and have the user initiate the retry.
            bool retry      = false;
            int  retryCount = 0;

            do
            {
                retry = false;
                try
                {
                    result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(caResourceIdScope);

                    return("protected API successfully called");
                }
                catch (MsalUiRequiredException ex)
                {
                    await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync((caResourceIdScope),
                                                                                         ex, HttpContext.Current.Response);

                    throw new HttpResponseException(new HttpResponseMessage {
                        StatusCode = HttpStatusCode.Forbidden
                    });
                }
            } while ((retry == true) && (retryCount < 1));

            /*
             * You can now use this  access token to accesss our Conditional-Access protected Web API using On-behalf-of
             * Use this code below to call the downstream Web API OBO
             *
             * string oboAccessToken = result.AccessToken;
             * private HttpClient httpClient = new HttpClient();
             * httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
             * HttpResponseMessage response = await httpClient.GetAsync(WebAPI2HttpEndpoint (App ID URI + "/endpoint");
             */
        }
        private void InitializeTokenAcquisitionObjects()
        {
            _msalTestTokenCacheProvider = new MsalTestTokenCacheProvider(
                _provider.GetService <IMemoryCache>(),
                _provider.GetService <IOptions <MsalMemoryTokenCacheOptions> >());

            _tokenAcquisition = new TokenAcquisition(
                _msalTestTokenCacheProvider,
                MockHttpContextAccessor.CreateMockHttpContextAccessor(),
                _provider.GetService <IOptions <MicrosoftIdentityOptions> >(),
                _provider.GetService <IOptions <ConfidentialClientApplicationOptions> >(),
                _provider.GetService <IHttpClientFactory>(),
                _provider.GetService <ILogger <TokenAcquisition> >(),
                _provider);
        }
Esempio n. 8
0
        //[MsalUiRequiredExceptionFilter(Scopes = new[] { "User.Read" })]
        public async Task <IActionResult> Test()
        {
            var token = await TokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { "https://mrs-prod.ame.gbl/mrs-RDInfra-prod/user_impersonation" });

            var httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri("https://rdweb.wvd.microsoft.com/");
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            httpClient.DefaultRequestHeaders.Add("Accept", "application/x-msts-radc-discovery+xml,text/xml");
            httpClient.DefaultRequestHeaders.Add("x-ms-correlation-id", "bc7a963a-3f8e-484f-adc9-f5f939e40000");
            httpClient.DefaultRequestHeaders.Add("X-MS-User-Agent", "com.microsoft.rdc.html/1.0.20.2");
            var result = await httpClient.GetAsync("api/hubdiscovery/eventhubdiscovery.aspx");

            result = await httpClient.GetAsync("api/feeddiscovery/webfeeddiscovery.aspx");

            return(new OkObjectResult(result));
        }
        private void InitializeTokenAcquisitionObjects()
        {
            MergedOptions mergedOptions = _provider.GetRequiredService <IOptionsMonitor <MergedOptions> >().Get(OpenIdConnectDefaults.AuthenticationScheme);

            MergedOptions.UpdateMergedOptionsFromMicrosoftIdentityOptions(_microsoftIdentityOptionsMonitor.Get(OpenIdConnectDefaults.AuthenticationScheme), mergedOptions);
            MergedOptions.UpdateMergedOptionsFromConfidentialClientApplicationOptions(_applicationOptionsMonitor.Get(OpenIdConnectDefaults.AuthenticationScheme), mergedOptions);

            _msalTestTokenCacheProvider = new MsalTestTokenCacheProvider(
                _provider.GetService <IMemoryCache>(),
                _provider.GetService <IOptions <MsalMemoryTokenCacheOptions> >());

            _tokenAcquisition = new TokenAcquisition(
                _msalTestTokenCacheProvider,
                MockHttpContextAccessor.CreateMockHttpContextAccessor(),
                _provider.GetService <IOptionsMonitor <MergedOptions> >(),
                _provider.GetService <IHttpClientFactory>(),
                _provider.GetService <ILogger <TokenAcquisition> >(),
                _provider);
            _tokenAcquisition.GetOptions(OpenIdConnectDefaults.AuthenticationScheme, out string effectiveAuthenticationScheme);
            Assert.Equal(OpenIdConnectDefaults.AuthenticationScheme, effectiveAuthenticationScheme);
        }
Esempio n. 10
0
        private void InitializeTokenAcquisitionObjects()
        {
            IOptions <MicrosoftIdentityOptions>             microsoftIdentityOptions = _provider.GetService <IOptions <MicrosoftIdentityOptions> >();
            IOptions <MsalMemoryTokenCacheOptions>          tokenOptions             = _provider.GetService <IOptions <MsalMemoryTokenCacheOptions> >();
            IOptions <ConfidentialClientApplicationOptions> ccOptions = _provider.GetService <IOptions <ConfidentialClientApplicationOptions> >();
            ILogger <TokenAcquisition> logger            = _provider.GetService <ILogger <TokenAcquisition> >();
            IHttpClientFactory         httpClientFactory = _provider.GetService <IHttpClientFactory>();

            IHttpContextAccessor httpContextAccessor = CreateMockHttpContextAccessor();

            _msalTestTokenCacheProvider = new MsalTestTokenCacheProvider(
                _provider.GetService <IMemoryCache>(),
                tokenOptions);

            _tokenAcquisition = new TokenAcquisition(
                _msalTestTokenCacheProvider,
                httpContextAccessor,
                microsoftIdentityOptions,
                ccOptions,
                httpClientFactory,
                logger);
        }
Esempio n. 11
0
        public async Task <TokenAcquisition> GetTokenInfoAsync(UserAccount account, ClientPortionTransferItem project)
        {
            var tokenInfo = new TokenAcquisition();

            if (account != null && account.HasValue && project != null)
            {
                var cookieJar = new CookieContainer();
                using (var handler = new HttpClientHandler
                {
                    CookieContainer = cookieJar,
                    UseCookies = true,
                })
                {
                    using (var client = CreateHttpClient(handler))
                    {
                        var Uri = CreateUri($"/CommissionedAcquisition?projectId={project.projectId}&currentPrice={project.minTransferingPrice}");

                        foreach (Cookie token in account.TokenOffical)
                        {
                            cookieJar.Add(Uri, new Cookie(token.Name, token.Value));
                        }

                        var response = await client.GetAsync(Uri);

                        if (response.IsSuccessStatusCode)
                        {
                            var html = await response.Content.ReadAsStringAsync();

                            RetrieveToken(html, tokenInfo);
                        }
                    }
                }
            }

            return(tokenInfo);
        }
Esempio n. 12
0
        private void RetrieveToken(string html, TokenAcquisition tokenInfo)
        {
            var tokenAcquire = Regex.Match(html, "TOKEN_ACQUIRE.*?(/>)", RegexOptions.IgnoreCase);

            if (tokenAcquire.Success)
            {
                var queryToken = Regex.Match(tokenAcquire.Value, "value=(\"|').*(\"|')", RegexOptions.IgnoreCase);
                if (queryToken.Success)
                {
                    tokenInfo.TokenAcquire = queryToken.Value.Replace("value=", string.Empty).Replace("\"", string.Empty).Replace("'", string.Empty).Trim();
                }
            }

            var tokenKey = Regex.Match(html, "tockenKey.*?(/>)", RegexOptions.IgnoreCase);

            if (tokenKey.Success)
            {
                var queryToken = Regex.Match(tokenKey.Value, "value=(\"|').*(\"|')", RegexOptions.IgnoreCase);
                if (queryToken.Success)
                {
                    tokenInfo.TokenKey = queryToken.Value.Replace("value=", string.Empty).Replace("\"", string.Empty).Replace("'", string.Empty).Trim();
                }
            }
        }
Esempio n. 13
0
        public static async Task <UserProfile> CallGraphAPIOnBehalfOfUser()
        {
            UserProfile          profile     = null;
            string               accessToken = null;
            AuthenticationResult result      = null;

            // In the case of a transient error, retry once after 1 second, then abandon.
            // Retrying is optional.  It may be better, for your application, to return an error immediately to the user and have the user initiate the retry.
            bool retry      = false;
            int  retryCount = 0;

            do
            {
                retry = false;
                try
                {
                    //_tokenAcquisition = new TokenAcquisition(SetOptions.SetMicrosoftIdOptions(), SetOptions.SetConClientAppOptions());
                    _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig());
                    result            = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(requestedScopes);

                    accessToken = result.AccessToken;
                }
                catch (MsalException ex)
                {
                    if (ex.ErrorCode == SERVICE_UNAVAILABLE)
                    {
                        // Transient error, OK to retry.
                        retry = true;
                        retryCount++;
                        Thread.Sleep(1000);
                    }
                }
            } while ((retry == true) && (retryCount < 1));

            if (accessToken == null)
            {
                // An unexpected error occurred.
                return(null);
            }

            //
            // Call the Graph API and retrieve the user's profile.
            //
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphUserUrl);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            //
            // Return the user's profile.
            //
            if (response.IsSuccessStatusCode)
            {
                string responseString = await response.Content.ReadAsStringAsync();

                profile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                return(profile);
            }

            // An unexpected error occurred calling the Graph API.  Return a null profile.
            return(null);
        }