public async Task <HttpResponse> SendPostAsync(Uri endpoint, IDictionary <string, string> headers, IDictionary <string, string> bodyParameters, ICoreLogger logger)
        {
            await Task.Delay(ParallelRequestsTests.NetworkAccessPenaltyMs).ConfigureAwait(false);

            if (endpoint.AbsoluteUri.Equals("https://login.microsoftonline.com/my-utid/oauth2/v2.0/token"))
            {
                bodyParameters.TryGetValue(OAuth2Parameter.RefreshToken, out string rtSecret);

                return(new HttpResponse()
                {
                    Body = GetTokenResponseForRt(rtSecret),
                    StatusCode = System.Net.HttpStatusCode.OK
                });
            }

            Assert.Fail("Only refresh flow is supported");
            return(null);
        }
 public Netstandard13PlatformProxy(ICoreLogger logger)
     : base(logger)
 {
 }
コード例 #3
0
        public static List <MsalRefreshTokenCacheItem> GetAllAdalEntriesForMsal(
            ICoreLogger logger,
            ILegacyCachePersistence legacyCachePersistence,
            IEnumerable <string> environmentAliases,
            string clientId,
            string upn,
            string uniqueId)
        {
            try
            {
                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary =
                    AdalCacheOperations.Deserialize(logger, legacyCachePersistence.LoadCache());
                // filter by client id and environment first
                // TODO - authority check needs to be updated for alias check
                List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > listToProcess =
                    dictionary.Where(p =>
                                     p.Key.ClientId.Equals(clientId, StringComparison.OrdinalIgnoreCase) &&
                                     environmentAliases.Contains(new Uri(p.Key.Authority).Host)).ToList();

                // if upn is provided then use it to filter
                if (!string.IsNullOrEmpty(upn))
                {
                    List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > upnEntries =
                        listToProcess.Where(p => upn.Equals(p.Key.DisplayableId, StringComparison.OrdinalIgnoreCase)).ToList();

                    if (upnEntries.Any())
                    {
                        listToProcess = upnEntries;
                    }
                }

                // if userId is provided then use it to filter
                if (!string.IsNullOrEmpty(uniqueId))
                {
                    List <KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> > uniqueIdEntries =
                        listToProcess.Where(p => uniqueId.Equals(p.Key.UniqueId, StringComparison.OrdinalIgnoreCase)).ToList();
                    if (uniqueIdEntries.Any())
                    {
                        listToProcess = uniqueIdEntries;
                    }
                }
                List <MsalRefreshTokenCacheItem> list = new List <MsalRefreshTokenCacheItem>();
                foreach (KeyValuePair <AdalTokenCacheKey, AdalResultWrapper> pair in listToProcess)
                {
                    string homeAccountId = null;
                    if (!string.IsNullOrEmpty(pair.Value.RawClientInfo))
                    {
                        homeAccountId = ClientInfo.CreateFromJson(pair.Value.RawClientInfo).ToAccountIdentifier();
                    }

                    list.Add(new MsalRefreshTokenCacheItem(
                                 new Uri(pair.Key.Authority).Host,
                                 pair.Key.ClientId,
                                 pair.Value.RefreshToken,
                                 pair.Value.RawClientInfo,
                                 familyId: null,
                                 homeAccountId: homeAccountId));
                }

                return(list);
            }
            catch (Exception ex)
            {
                logger.WarningPiiWithPrefix(ex, "An error occurred while searching for refresh tokens in ADAL format in the cache for MSAL. " +
                                            "For details please see https://aka.ms/net-cache-persistence-errors. ");

                return(new List <MsalRefreshTokenCacheItem>());
            }
        }
コード例 #4
0
 public CoreLoggerMiddleware(RequestDelegate next, ICoreLogger logger)
 {
     _next   = next;
     _logger = logger;
 }
コード例 #5
0
 public AadPlugin(IWamProxy wamProxy, IWebAccountProviderFactory webAccountProviderFactory, ICoreLogger logger)
 {
     _wamProxy = wamProxy;
     _webAccountProviderFactory = webAccountProviderFactory;
     _logger = logger;
 }
コード例 #6
0
 public override List <MsalAccessTokenCacheItem> GetAllAccessTokens(string partitionKey = null, ICoreLogger requestlogger = null)
 {
     Assert.IsNotNull(partitionKey);
     return(base.GetAllAccessTokens(partitionKey, requestlogger));
 }
コード例 #7
0
        private async Task <HttpResponse> ExecuteWithRetryAsync(
            Uri endpoint,
            IDictionary <string, string> headers,
            HttpContent body,
            HttpMethod method,
            ICoreLogger logger,
            bool doNotThrow = false,
            bool retry      = true,
            CancellationToken cancellationToken = default)
        {
            Exception    timeoutException = null;
            bool         isRetryable      = false;
            bool         is5xxError       = false;
            HttpResponse response         = null;

            try
            {
                HttpContent clonedBody = body;
                if (body != null)
                {
                    // Since HttpContent would be disposed by underlying client.SendAsync(),
                    // we duplicate it so that we will have a copy in case we would need to retry
                    clonedBody = await CloneHttpContentAsync(body).ConfigureAwait(false);
                }

                response = await ExecuteAsync(endpoint, headers, clonedBody, method, logger, cancellationToken).ConfigureAwait(false);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(response);
                }

                logger.Info(string.Format(CultureInfo.InvariantCulture,
                                          MsalErrorMessage.HttpRequestUnsuccessful,
                                          (int)response.StatusCode, response.StatusCode));


                is5xxError  = (int)response.StatusCode >= 500 && (int)response.StatusCode < 600;
                isRetryable = is5xxError && !HasRetryAfterHeader(response);
            }
            catch (TaskCanceledException exception)
            {
                logger.Error("The HTTP request failed or it was canceled. " + exception.Message);
                isRetryable = true;

                if (cancellationToken.IsCancellationRequested)
                {
                    isRetryable = false;
                }

                timeoutException = exception;
            }

            if (isRetryable && retry)
            {
                logger.Info("Retrying one more time..");
                await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

                return(await ExecuteWithRetryAsync(
                           endpoint,
                           headers,
                           body,
                           method,
                           logger,
                           doNotThrow,
                           retry : false).ConfigureAwait(false));
            }

            logger.Warning("Request retry failed.");
            if (timeoutException != null)
            {
                throw new MsalServiceException(
                          MsalError.RequestTimeout,
                          "Request to the endpoint timed out.",
                          timeoutException);
            }

            if (doNotThrow)
            {
                return(response);
            }

            if (is5xxError)
            {
                throw MsalServiceExceptionFactory.FromHttpResponse(
                          MsalError.ServiceNotAvailable,
                          "Service is unavailable to process the request",
                          response);
            }

            return(response);
        }
 /// <inheritdoc />
 public NetDesktopPlatformProxy(ICoreLogger logger)
     : base(logger)
 {
 }
コード例 #9
0
 public SearchController(ISearchService searchService, ICoreLogger logger)
 {
     _searchService = searchService;
     _logger        = logger;
 }
 public SeleniumWebUI(Action <IWebDriver> seleniumAutomationLogic, TestContext testContext, ICoreLogger logger = null)
 {
     _seleniumAutomationLogic = seleniumAutomationLogic;
     _testContext             = testContext;
     _logger = logger ?? new TraceLogger("[SeleniumWebUi]");
 }
コード例 #11
0
 /// <summary>
 /// EmpAdressController Constructor
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="empAdressService"></param>
 public EmpAdressController(ICoreLogger logger, IEmpAdressService empAdressService)
 {
     _logger           = logger;
     _empAdressService = empAdressService;
 }
コード例 #12
0
        internal static MsalTokenResponse CreateMsalResponseFromWamResponse(
            IWebTokenRequestResultWrapper wamResponse,
            IWamPlugin wamPlugin,
            string clientId,
            ICoreLogger logger,
            bool isInteractive)
        {
            string internalErrorCode = null;
            string errorMessage;
            string errorCode;

            switch (wamResponse.ResponseStatus)
            {
            case WebTokenRequestStatus.Success:
                logger.Info("WAM response status success");
                return(wamPlugin.ParseSuccessfullWamResponse(wamResponse.ResponseData[0], out _));

            // Account Switch occurs when a login hint is passed to WAM but the user chooses a different account for login.
            // MSAL treats this as a success scenario
            case WebTokenRequestStatus.AccountSwitch:
                logger.Info("WAM response status account switch. Treating as success");
                return(wamPlugin.ParseSuccessfullWamResponse(wamResponse.ResponseData[0], out _));

            case WebTokenRequestStatus.UserInteractionRequired:
                errorCode =
                    wamPlugin.MapTokenRequestError(wamResponse.ResponseStatus, wamResponse.ResponseError?.ErrorCode ?? 0, isInteractive);
                internalErrorCode = (wamResponse.ResponseError?.ErrorCode ?? 0).ToString(CultureInfo.InvariantCulture);
                errorMessage      = WamErrorPrefix +
                                    $"Wam plugin {wamPlugin.GetType()}" +
                                    $" Error code: {internalErrorCode}" +
                                    $" Error Message: " + wamResponse.ResponseError?.ErrorMessage;
                break;

            case WebTokenRequestStatus.UserCancel:
                errorCode    = MsalError.AuthenticationCanceledError;
                errorMessage = MsalErrorMessage.AuthenticationCanceled;
                break;

            case WebTokenRequestStatus.ProviderError:
                errorCode =
                    wamPlugin.MapTokenRequestError(wamResponse.ResponseStatus, wamResponse.ResponseError?.ErrorCode ?? 0, isInteractive);
                errorMessage =
                    $"{WamErrorPrefix} {wamPlugin.GetType()} \n" +
                    $" Error Code: {errorCode} \n" +
                    $" Error Message: {wamResponse.ResponseError?.ErrorMessage} \n" +
                    $" Possible causes: \n " +
                    $"- Invalid redirect uri - ensure you have configured the following url in the AAD portal App Registration: {GetExpectedRedirectUri(clientId)} \n" +
                    $"- No Internet connection \n" +
                    $"Please see https://aka.ms/msal-net-wam for details about Windows Broker integration";

                internalErrorCode = (wamResponse.ResponseError?.ErrorCode ?? 0).ToString(CultureInfo.InvariantCulture);
                break;

            default:
                errorCode         = MsalError.UnknownBrokerError;
                internalErrorCode = wamResponse.ResponseError.ErrorCode.ToString(CultureInfo.InvariantCulture);
                errorMessage      = $"Unknown WebTokenRequestStatus {wamResponse.ResponseStatus} (internal error code {internalErrorCode})";
                break;
            }

            return(new MsalTokenResponse()
            {
                Error = errorCode,
                ErrorCodes = internalErrorCode != null ? new[] { internalErrorCode } : null,
                ErrorDescription = errorMessage
            });
        }
 public Task <HttpResponse> SendPostForceResponseAsync(Uri uri, Dictionary <string, string> headers, StringContent body, ICoreLogger logger)
 {
     throw new NotImplementedException();
 }
 public Task <HttpResponse> SendPostAsync(Uri endpoint, IDictionary <string, string> headers, HttpContent body, ICoreLogger logger)
 {
     throw new NotImplementedException();
 }
コード例 #15
0
 public iOSBroker(ICoreLogger logger, ICryptographyManager cryptoManager, CoreUIParent uIParent)
 {
     _logger        = logger;
     _cryptoManager = cryptoManager;
     _uIParent      = uIParent;
 }
コード例 #16
0
 /// <summary>
 /// EmpPositionDetailController Constructor
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="empPositionDetailService"></param>
 public EmpPositionDetailController(ICoreLogger logger, IEmpPositionDetailService empPositionDetailService)
 {
     _logger = logger;
     _empPositionDetailService = empPositionDetailService;
 }
コード例 #17
0
 public AppAccessorWithPartitionAsserts(
     ICoreLogger logger,
     CacheOptions tokenCacheAccessorOptions) : base(logger, tokenCacheAccessorOptions)
 {
 }
 /// <inheritdoc />
 public void LogParameters(ICoreLogger logger)
 {
 }
コード例 #19
0
        public override List <MsalRefreshTokenCacheItem> GetAllRefreshTokens(string partitionKey = null, ICoreLogger requestlogger = null)
        {
            Assert.IsNotNull(partitionKey);

            Assert.Fail("App token cache - do not call GetAllRefreshTokens");
            throw new InvalidOperationException();
        }
コード例 #20
0
 public AndroidPlatformProxy(ICoreLogger logger) : base(logger)
 {
 }
コード例 #21
0
 public void TestInitialize()
 {
     // Methods in XmsCliTelemTests log errors when parsing response headers;
     _coreLogger     = Substitute.For <ICoreLogger>();
     _requestContext = new RequestContext(null, _coreLogger);
 }
コード例 #22
0
 public static void SetAuthorizationResult(AuthorizationResult authorizationResultInput, ICoreLogger logger)
 {
     if (returnedUriReady != null)
     {
         authorizationResult = authorizationResultInput;
         returnedUriReady.Release();
     }
     else
     {
         logger?.Info("No pending request for response from web ui.");
     }
 }
        internal void LogParameters(ICoreLogger logger)
        {
            logger.Info("WebView2Options configured");

            logger.Info($"Title: {Title}");
        }
コード例 #24
0
 public DpApiEncryptedFileProvider(ICryptographyManager cryptographyManager, ICoreLogger logger)
 {
     _cryptographyManager = cryptographyManager;
     _logger = logger;
 }
コード例 #25
0
 public PlatformProxy(ICoreLogger logger)
     : base(logger)
 {
 }
コード例 #26
0
 /// <summary>
 /// ClientsController Constructor
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="clientService"></param>
 public EmployeesController(ICoreLogger logger, IEmpEmployeePkService empEmployeePkService)
 {
     _logger = logger;
     _empEmployeePkService = empEmployeePkService;
 }
コード例 #27
0
        public static void WriteAdalRefreshToken(
            ICoreLogger logger,
            ILegacyCachePersistence legacyCachePersistence,
            MsalRefreshTokenCacheItem rtItem,
            MsalIdTokenCacheItem idItem,
            string authority,
            string uniqueId,
            string scope)
        {
            try
            {
                if (rtItem == null)
                {
                    logger.Info("No refresh token available. Skipping writing to ADAL legacy cache.");
                    return;
                }

                if (!string.IsNullOrEmpty(rtItem.FamilyId))
                {
                    logger.Info("Not writing FRT in ADAL legacy cache");
                    return;
                }

                //Using scope instead of resource because that value does not exist. STS should return it.
                AdalTokenCacheKey key = new AdalTokenCacheKey(authority, scope, rtItem.ClientId, TokenSubjectType.User,
                                                              uniqueId, idItem.IdToken.PreferredUsername);
                AdalResultWrapper wrapper = new AdalResultWrapper()
                {
                    Result = new AdalResult()
                    {
                        UserInfo = new AdalUserInfo()
                        {
                            UniqueId      = uniqueId,
                            DisplayableId = idItem.IdToken.PreferredUsername
                        }
                    },
                    RefreshToken  = rtItem.Secret,
                    RawClientInfo = rtItem.RawClientInfo,
                    //ResourceInResponse is needed to treat RT as an MRRT. See IsMultipleResourceRefreshToken
                    //property in AdalResultWrapper and its usage. Stronger design would be for the STS to return resource
                    //for which the token was issued as well on v2 endpoint.
                    ResourceInResponse = scope
                };

                IDictionary <AdalTokenCacheKey, AdalResultWrapper> dictionary = AdalCacheOperations.Deserialize(
                    logger,
                    legacyCachePersistence.LoadCache());

                dictionary[key] = wrapper;
                legacyCachePersistence.WriteCache(AdalCacheOperations.Serialize(logger, dictionary));
            }
            catch (Exception ex)
            {
                if (!string.Equals(rtItem?.Environment, idItem?.Environment, StringComparison.OrdinalIgnoreCase))
                {
                    logger.Error(DifferentEnvError);
                }

                if (!string.Equals(rtItem?.Environment, new Uri(authority).Host, StringComparison.OrdinalIgnoreCase))
                {
                    logger.Error(DifferentAuthorityError);
                }

                logger.WarningPiiWithPrefix(ex, "An error occurred while writing MSAL refresh token to the cache in ADAL format. " +
                                            "For details please see https://aka.ms/net-cache-persistence-errors. ");
            }
        }
 public OAuth2Client(ICoreLogger logger, IHttpManager httpManager, ITelemetryManager telemetryManager)
 {
     _headers          = new Dictionary <string, string>(MsalIdHelper.GetMsalIdParameters(logger));
     _httpManager      = httpManager ?? throw new ArgumentNullException(nameof(httpManager));
     _telemetryManager = telemetryManager ?? throw new ArgumentNullException(nameof(telemetryManager));
 }
コード例 #29
0
        public async Task <HttpResponse> SendGetAsync(Uri endpoint, IDictionary <string, string> headers, ICoreLogger logger, bool retry = true, CancellationToken cancellationToken = default)
        {
            // simulate delay and also add complexity due to thread context switch
            await Task.Delay(ParallelRequestsTests.NetworkAccessPenaltyMs).ConfigureAwait(false);

            if (endpoint.AbsoluteUri.StartsWith("https://login.microsoftonline.com/common/discovery/instance?api-version=1.1"))
            {
                return(new HttpResponse()
                {
                    Body = TestConstants.DiscoveryJsonResponse,
                    StatusCode = System.Net.HttpStatusCode.OK
                });
            }

            Assert.Fail("Only instance discovery is supported");
            return(null);
        }
コード例 #30
0
        public static void TryThrowServiceException(string thumbprint, ThrottlingCache cache, ICoreLogger logger, string providerName)
        {
            if (cache.TryGetOrRemoveExpired(thumbprint, logger, out var ex))
            {
                logger.WarningPii(
                    $"[Throttling] Exception thrown because of throttling rule {providerName} - thumbprint: {thumbprint}",
                    $"[Throttling] Exception thrown because of throttling rule {providerName}");

                // mark the exception for logging purposes
                throw new MsalThrottledServiceException(ex);
            }
        }