private static Assembly LoadPlatformSpecificAssembly()
        {
            // For security reasons, it is important to have PublicKeyToken mentioned referencing the assembly.
            const string PlatformSpecificAssemblyNameTemplate = "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform, Version={0}, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

            string platformSpecificAssemblyName = string.Format(CultureInfo.CurrentCulture, PlatformSpecificAssemblyNameTemplate, AdalIdHelper.GetAdalVersion());

            try
            {
                return(Assembly.Load(new AssemblyName(platformSpecificAssemblyName)));
            }
            catch (FileNotFoundException ex)
            {
                throw new AdalException(AdalError.AssemblyNotFound, string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.AssemblyNotFoundTemplate, platformSpecificAssemblyName), ex);
            }
            catch (Exception ex) // FileLoadException is missing from PCL
            {
                throw new AdalException(AdalError.AssemblyLoadFailed, string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.AssemblyLoadFailedTemplate, platformSpecificAssemblyName), ex);
            }
        }
 static AuthenticationContext()
 {
     PlatformPlugin.Logger.Information(null, string.Format(CultureInfo.CurrentCulture, "ADAL {0} with assembly version '{1}', file version '{2}' and informational version '{3}' is running...",
                                                           PlatformPlugin.PlatformInformation.GetProductName(), AdalIdHelper.GetAdalVersion(), AdalIdHelper.GetAssemblyFileVersion(), AdalIdHelper.GetAssemblyInformationalVersion()));
 }
        protected AcquireTokenHandlerBase(RequestData requestData)
        {
            this.Authenticator     = requestData.Authenticator;
            this.CallState         = CreateCallState(this.Authenticator.CorrelationId);
            brokerHelper.CallState = this.CallState;

            CallState.Logger.Information(null, string.Format(CultureInfo.CurrentCulture,
                                                             "ADAL {0} with assembly version '{1}', file version '{2}' and informational version '{3}' is running...",
                                                             platformInformation.GetProductName(), AdalIdHelper.GetAdalVersion(),
                                                             AdalIdHelper.GetAssemblyFileVersion(), AdalIdHelper.GetAssemblyInformationalVersion()));

            CallState.Logger.Information(this.CallState,
                                         string.Format(CultureInfo.CurrentCulture,
                                                       "=== Token Acquisition started:\n\tAuthority: {0}\n\tResource: {1}\n\tClientId: {2}\n\tCacheType: {3}\n\tAuthentication Target: {4}\n\t",
                                                       requestData.Authenticator.Authority, requestData.Resource, requestData.ClientKey.ClientId,
                                                       (tokenCache != null)
                        ? tokenCache.GetType().FullName +
                                                       string.Format(CultureInfo.CurrentCulture, " ({0} items)", tokenCache.Count)
                        : "null",
                                                       requestData.SubjectType));

            this.tokenCache = requestData.TokenCache;

            if (string.IsNullOrWhiteSpace(requestData.Resource))
            {
                throw new ArgumentNullException("resource");
            }

            this.Resource         = (requestData.Resource != NullResource) ? requestData.Resource : null;
            this.ClientKey        = requestData.ClientKey;
            this.TokenSubjectType = requestData.SubjectType;

            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache  = (tokenCache != null);
            this.SupportADFS   = false;

            this.brokerParameters = new Dictionary <string, string>();
            brokerParameters[BrokerParameter.Authority]     = requestData.Authenticator.Authority;
            brokerParameters[BrokerParameter.Resource]      = requestData.Resource;
            brokerParameters[BrokerParameter.ClientId]      = requestData.ClientKey.ClientId;
            brokerParameters[BrokerParameter.CorrelationId] = this.CallState.CorrelationId.ToString();
            brokerParameters[BrokerParameter.ClientVersion] = AdalIdHelper.GetAdalVersion();
            this.ResultEx = null;

            CacheQueryData.ExtendedLifeTimeEnabled = requestData.ExtendedLifeTimeEnabled;
        }
 static AuthenticationContext()
 {
     Logger.Information(null, string.Format("ADAL {0} with assembly version '{1}', file version '{2}' and informational version '{3}' is running...",
                                            PlatformSpecificHelper.GetProductName(), AdalIdHelper.GetAdalVersion(), AdalIdHelper.GetAssemblyFileVersion(), AdalIdHelper.GetAssemblyInformationalVersion()));
 }
Beispiel #5
0
        private async Task <T> GetResponseAsync <T>(bool respondToDeviceAuthChallenge)
        {
            T typedResponse = default(T);
            IHttpWebResponse response;

            try
            {
                if (PlatformPlugin.HttpClientFactory.AddAdditionalHeaders)
                {
                    IDictionary <string, string> adalIdHeaders = AdalIdHelper.GetAdalIdParameters();
                    foreach (KeyValuePair <string, string> kvp in adalIdHeaders)
                    {
                        this.Client.Headers[kvp.Key] = kvp.Value;
                    }
                }

                //add pkeyauth header
                this.Client.Headers[DeviceAuthHeaderName] = DeviceAuthHeaderValue;
                using (response = await this.Client.GetResponseAsync().ConfigureAwait(false))
                {
                    typedResponse = EncodingHelper.DeserializeResponse <T>(response.ResponseString);
                }
            }
            catch (HttpRequestWrapperException ex)
            {
                if (ex.InnerException is TaskCanceledException)
                {
                    Resiliency = true;
                    PlatformPlugin.Logger.Information(this.CallState, "Network timeout - " + ex.InnerException.Message);
                }

                if (!this.isDeviceAuthChallenge(ex.WebResponse, respondToDeviceAuthChallenge))
                {
                    AdalServiceException serviceEx;
                    if (ex.WebResponse != null)
                    {
                        TokenResponse tokenResponse = TokenResponse.CreateFromErrorResponse(ex.WebResponse);
                        string[]      errorCodes    = tokenResponse.ErrorCodes ?? new[] { ex.WebResponse.StatusCode.ToString() };
                        serviceEx = new AdalServiceException(tokenResponse.Error, tokenResponse.ErrorDescription,
                                                             errorCodes, ex);

                        if ((ex.WebResponse.StatusCode.Equals(HttpStatusCode.InternalServerError)) ||
                            (ex.WebResponse.StatusCode).Equals(HttpStatusCode.GatewayTimeout) ||
                            (ex.WebResponse.StatusCode).Equals(HttpStatusCode.ServiceUnavailable))
                        {
                            PlatformPlugin.Logger.Information(this.CallState, "HttpStatus code: " + ex.WebResponse.StatusCode + " - " + ex.InnerException.Message);
                            Resiliency = true;
                        }
                    }
                    else
                    {
                        serviceEx = new AdalServiceException(AdalError.Unknown, ex);
                    }

                    if (Resiliency)
                    {
                        if (RetryOnce)
                        {
                            await Task.Delay(DelayTimePeriodMilliSeconds).ConfigureAwait(false);

                            RetryOnce = false;
                            PlatformPlugin.Logger.Information(this.CallState, "Retrying one more time..");
                            return(await this.GetResponseAsync <T>(respondToDeviceAuthChallenge).ConfigureAwait(false));
                        }

                        PlatformPlugin.Logger.Information(this.CallState,
                                                          "Retry Failed - " + ex.InnerException.Message);
                    }

                    PlatformPlugin.Logger.Error(CallState, serviceEx);
                    throw serviceEx;
                }
                else
                {
                    response = ex.WebResponse;
                }
            }
            //check for pkeyauth challenge
            if (this.isDeviceAuthChallenge(response, respondToDeviceAuthChallenge))
            {
                return(await HandleDeviceAuthChallenge <T>(response).ConfigureAwait(false));
            }

            return(typedResponse);
        }
        private async Task <T> GetResponseAsync <T>(string endpointType, bool respondToDeviceAuthChallenge)
        {
            T typedResponse = default(T);
            IHttpWebResponse response;
            ClientMetrics    clientMetrics = new ClientMetrics();

            try
            {
                clientMetrics.BeginClientMetricsRecord(this.CallState);

                if (PlatformPlugin.HttpClientFactory.AddAdditionalHeaders)
                {
                    Dictionary <string, string> clientMetricsHeaders = clientMetrics.GetPreviousRequestRecord(this.CallState);
                    foreach (KeyValuePair <string, string> kvp in clientMetricsHeaders)
                    {
                        this.Client.Headers[kvp.Key] = kvp.Value;
                    }

                    IDictionary <string, string> adalIdHeaders = AdalIdHelper.GetAdalIdParameters();
                    foreach (KeyValuePair <string, string> kvp in adalIdHeaders)
                    {
                        this.Client.Headers[kvp.Key] = kvp.Value;
                    }
                }

                //add pkeyauth header
                this.Client.Headers[DeviceAuthHeaderName] = DeviceAuthHeaderValue;
                using (response = await this.Client.GetResponseAsync())
                {
                    typedResponse = DeserializeResponse <T>(response.ResponseStream);
                    clientMetrics.SetLastError(null);
                }
            }
            catch (HttpRequestWrapperException ex)
            {
                if (!this.isDeviceAuthChallenge(endpointType, ex.WebResponse, respondToDeviceAuthChallenge))
                {
                    AdalServiceException serviceEx;
                    if (ex.WebResponse != null)
                    {
                        TokenResponse tokenResponse = TokenResponse.CreateFromErrorResponse(ex.WebResponse);
                        string[]      errorCodes    = tokenResponse.ErrorCodes ?? new[] { ex.WebResponse.StatusCode.ToString() };
                        serviceEx = new AdalServiceException(tokenResponse.Error, tokenResponse.ErrorDescription,
                                                             errorCodes, ex);
                    }
                    else
                    {
                        serviceEx = new AdalServiceException(AdalError.Unknown, ex);
                    }

                    clientMetrics.SetLastError(serviceEx.ServiceErrorCodes);
                    PlatformPlugin.Logger.Error(CallState, serviceEx);
                    throw serviceEx;
                }
                else
                {
                    response = ex.WebResponse;
                }
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(endpointType, this.CallState);
            }

            //check for pkeyauth challenge
            if (this.isDeviceAuthChallenge(endpointType, response, respondToDeviceAuthChallenge))
            {
                return(await HandleDeviceAuthChallenge <T>(endpointType, response));
            }

            return(typedResponse);
        }