public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            string input = string.Empty;

            AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
                                                                           "qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");

            Assert.Equal(
                "Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
                auth.ToString());
            response.Headers.ProxyAuthenticate.Add(auth);
            input += auth.ToString();

            auth = new AuthenticationHeaderValue("Negotiate");
            Assert.Equal("Negotiate", auth.ToString());
            response.Headers.ProxyAuthenticate.Add(auth);
            input += ", " + auth.ToString();

            auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
            Assert.Equal("Custom", auth.ToString());
            response.Headers.ProxyAuthenticate.Add(auth);
            input += ", " + auth.ToString();

            string result = response.Headers.ProxyAuthenticate.ToString();

            Assert.Equal(input, result);
        }
예제 #2
0
        public async Task CheckAuthorizationHeader(string authorizationHeader)
        {
            var isRequestFinished = new TaskCompletionSource <object>();

            AuthenticationHeaderValue authHeader = null;
            var handler = new MockHttpMessageHandler((r, c) =>
            {
                authHeader = r.Headers.Authorization;
                isRequestFinished.SetResult(null);
                return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
            });

            var logger        = new NoopLogger();
            var mockConfig    = new MockConfigSnapshot(logger, secretToken: _secretToken, apiKey: _apiKey, flushInterval: "1s");
            var payloadSender = new PayloadSenderV2(logger, mockConfig,
                                                    Api.Service.GetDefaultService(mockConfig, logger), new Api.System(), handler, /* dbgName: */ nameof(ApiKeyFeatureContext));

            using (var agent = new ApmAgent(new TestAgentComponents(logger, mockConfig, payloadSender)))
            {
                agent.PayloadSender.QueueTransaction(new Transaction(agent, "TestName", "TestType"));
                await isRequestFinished.Task;
            }

            authHeader.Should().NotBeNull();
            authHeader.ToString().Should().Be(authorizationHeader);
        }
예제 #3
0
        public HttpResponseMessage Post(RegisterModel model)
        {
            try
            {
                if (Membership.ValidateUser(model.Email, model.Password))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Conflict, "Member is already existed"));
                }

                if (Membership.CreateUser(model.MemberName, model.Password, model.Email).Equals(default(MembershipUser)))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Member hasn't been registered"));
                }

                byte[] buffer = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", model.Email, model.Password));
                AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));

                return(Request.CreateResponse(HttpStatusCode.OK, new AuthorizationTicket {
                    Ticket = authHeader.ToString()
                }));
            }
            catch (Exception exc)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, exc.Message));
            }
        }
예제 #4
0
        /// <summary>
        /// Makes an HTTP(S) GET request to <seealso cref="requestUrl"/> and returns the result as (awaitable Task of) <seealso cref="string"/>.
        /// </summary>
        /// <param name="requestUrl">The entire request URL.</param>
        /// <param name="authenticationHeader"></param>
        /// <returns>An (awaitable Task of) <seealso cref="string"/></returns>
        /// <remarks>Will Authorise using the values of the SpotifyApiClientId and SpotifyApiClientSecret appSettings. See
        /// https://developer.spotify.com/web-api/authorization-guide/#client-credentials-flow </remarks>
        public static async Task <string> Get(
            this HttpClient http,
            string requestUrl,
            AuthenticationHeaderValue authenticationHeader)
        {
            //TODO: Implement if-modified-since support, serving from cache if response = 304

            if (string.IsNullOrEmpty(requestUrl))
            {
                throw new ArgumentNullException(requestUrl);
            }

            Logger.Debug(
                $"GET {requestUrl}. Token = {authenticationHeader?.ToString()?.Substring(0, 11)}...",
                nameof(RestHttpClient));

            http.DefaultRequestHeaders.Authorization = authenticationHeader;
            var response = await http.GetAsync(requestUrl);

            Logger.Information($"Got {requestUrl} {response.StatusCode}", nameof(RestHttpClient));

            await CheckForErrors(response);

            return(await response.Content.ReadAsStringAsync());
        }
예제 #5
0
        private static void container_BuildingRequest(object sender,
                                                      global::Microsoft.OData.Client.BuildingRequestEventArgs e)
        {
            var headerValue = new AuthenticationHeaderValue("Bearer", accessToken);

            e.Headers.Add("Authorization", headerValue.ToString());
        }
예제 #6
0
        bool ValidateAuthHeader(AuthenticationHeaderValue header, out string message)
        {
            message = string.Empty;
            var validate = ConfigurationManager.AppSettings["ValidateClientAuthHeader"];

            if (validate?.Equals("1") == false)
            {
                return(true);
            }

            if (header == null)
            {
                message = "Unknown authorization";
                return(false);
            }

            var clientAuthHeader = ConfigurationManager.AppSettings["ClientAuthHeader"];

            if (clientAuthHeader == null || clientAuthHeader?.Length == 0)
            {
                message = "No Authorization header value found";
                return(false);
            }

            if (clientAuthHeader.Equals(header.ToString()))
            {
                return(true);
            }

            message = "Unknown authorization";
            return(false);
        }
예제 #7
0
        public static IDictionary <string, string> ParseAuthHeader(AuthenticationHeaderValue header)
        {
            if (header == null)
            {
                return(null);
            }

            var retVal  = new Dictionary <string, string>();
            var raw     = header.Parameter;
            var regex   = new Regex("(\\w+)=((\\w+)|\"([^\"]+))");
            var matches = regex.Matches(raw);

            if (matches.Count > 0)
            {
                var groups = matches[0].Groups;
                var key    = groups[1].Value;
                var k      = groups[3];
                if (!k.Success)
                {
                    k = groups[4];
                }

                retVal[key]      = k.Value;
                retVal["Scheme"] = header.Scheme;
            }

            retVal["WWW-Authenticate"] = header.ToString();
            return(retVal);
        }
예제 #8
0
        /// <summary>
        /// Makes an HTTP(S) POST request to <seealso cref="requestUrl"/> with <seealso cref="formData"/> as the request body. Returns the result as (awaitable Task of) <seealso cref="string"/>.
        /// </summary>
        /// <param name="requestUrl">The entire request URL.</param>
        /// <param name="formData">The URL encoded formData in format "key1=value1&amp;key2=value2"</param>
        /// <param name="headerValue">An authentication header for the request.</param>
        /// <returns>An (awaitable Task of) <seealso cref="string"/> </returns>
        /// <remarks>Will Authorise using the values of the SpotifyApiClientId and SpotifyApiClientSecret appSettings. See
        /// https://developer.spotify.com/web-api/authorization-guide/#client-credentials-flow </remarks>
        public static async Task <string> Post(
            this HttpClient http,
            string requestUrl,
            string formData,
            AuthenticationHeaderValue headerValue)
        {
            if (string.IsNullOrEmpty(requestUrl))
            {
                throw new ArgumentNullException(requestUrl);
            }
            if (string.IsNullOrEmpty(formData))
            {
                throw new ArgumentNullException(formData);
            }

            Logger.Debug(
                $"POST {requestUrl}. Token = {headerValue?.ToString()?.Substring(0, 11)}...",
                nameof(RestHttpClient));

            http.DefaultRequestHeaders.Authorization = headerValue;
            var response =
                await
                http.PostAsync(requestUrl,
                               new StringContent(formData, Encoding.UTF8, "application/x-www-form-urlencoded"));

            Logger.Information($"Posted {requestUrl} {response.StatusCode}", nameof(RestHttpClient));

            await CheckForErrors(response);

            return(await response.Content.ReadAsStringAsync());
        }
        /// <summary>
        /// Verify the authentication header.
        /// </summary>
        /// <param name="header">Authentication header.</param>
        /// <param name="initial">Flag to indicate whether this is the initial verification call.</param>
        /// <param name="sessionToken">Session token associated with the authentication header.</param>
        /// <returns>True if the initial authentication header is valid; false otherwise.</returns>
        protected bool VerifyAuthenticationHeader(AuthenticationHeaderValue header, bool initial, out string sessionToken)
        {
            bool   verified            = false;
            string sessionTokenChecked = null;

            if (header != null)
            {
                AuthenticationUtils.GetSharedSecret sharedSecret;

                if (initial)
                {
                    sharedSecret = InitialSharedSecret;
                }
                else
                {
                    sharedSecret = SharedSecret;
                }

                if ("Basic".Equals(header.Scheme))
                {
                    verified = AuthenticationUtils.VerifyBasicAuthorisationToken(header.ToString(), sharedSecret, out sessionTokenChecked);
                }
                else if ("SIF_HMACSHA256".Equals(header.Scheme))
                {
                    verified = true;
                }
            }

            sessionToken = sessionTokenChecked;

            return(verified);
        }
예제 #10
0
        public async Task <ActionResult> Payment(Payment payment)
        {
            //var userIp = HttpContext.Request.Host;
            var _IP = "RemoteIp:" + Request.HttpContext.Connection.RemoteIpAddress.ToString() + " - LocalIpAddress:" +
                      Request.HttpContext.Connection.LocalIpAddress;

            String payendpoint  = configuration.GetValue <string>("SecurePay:Endpoint") + configuration.GetValue <string>("SecurePay:PayAPI");
            String merchantcode = configuration.GetValue <string>("SecurePay:MerchantCode");

            var authValue = new AuthenticationHeaderValue("Bearer", payment.AccessToken);

            var authValueString = authValue.ToString();

            var IdempotencyKey = Guid.NewGuid();

            client.DefaultRequestHeaders.Authorization = authValue;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Idempotency-Key", IdempotencyKey.ToString());

            var payModel = new PayModel
            {
                merchantCode = merchantcode,
                amount       = payment.Amount,
                token        = payment.Token,
                ip           = Request.HttpContext.Connection.RemoteIpAddress.ToString()
            };
            string json          = JsonConvert.SerializeObject(payModel);
            var    stringContent = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync(payendpoint, stringContent);

            var responseString = await response.Content.ReadAsStringAsync();

            return(Ok(responseString));
        }
예제 #11
0
        /// <summary>
        /// This method returns Base64 encoded values required for Basic Authentication
        /// </summary>
        public static string Base64EncodedBaiscAuth()
        {
            var byteArray = Encoding.ASCII.GetBytes($"{DEFAULT_USERNAME}:{DEFAULT_PASSWORD}");
            var clientAuthrizationHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            return(clientAuthrizationHeader.ToString());
        }
예제 #12
0
        static string EncodeBasicAuth(string UserName, string Password)
        {
            var byteArray = Encoding.UTF8.GetBytes($"{UserName}:{Password}");
            var clientAuthrizationHeader = new AuthenticationHeaderValue("Basic",
                                                                         Convert.ToBase64String(byteArray));

            return(clientAuthrizationHeader.ToString());
        }
        public override Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken)
        {
            var workItem = executingContext.Arguments.First().Value as HttpRequestMessage;
            ValidationPackage         validationPackage = new ValidationPackage();
            AuthenticationHeaderValue jwtInput          = workItem.Headers.Authorization;

            if (jwtInput != null)
            {
                String jwt = "";
                if (jwtInput.ToString().StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                {
                    jwt = jwtInput.ToString().Substring("Bearer ".Length).Trim();
                }

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

                if (!string.IsNullOrEmpty(jwt))
                {
                    try
                    {
                        validationPackage = ExtractClaims(jwt, handler);
                    }
                    catch (Exception e)
                    {
                        // log.Error("Exception caught while validating token", e);
                    }
                }
                else
                {
                    //log.Error("Auth Token begins with [" + jwtInput.ToString().Substring(0, 12) + "...]");
                }
            }

            if (!validationPackage.validToken)
            {
                workItem.Headers.Add("AuthorizationStatus", Convert.ToInt32(HttpStatusCode.Unauthorized).ToString());
            }
            else
            {
                workItem.Headers.Add("AuthorizationStatus", Convert.ToInt32(HttpStatusCode.Accepted).ToString());
            }

            return(base.OnExecutingAsync(executingContext, cancellationToken));
        }
예제 #14
0
        public GithubRepository(string connectionString, AuthenticationHeaderValue credentials, string organization)
        {
            _sqlConnection = new SqlConnection(connectionString);

            _client = new HttpClient();
            _client.DefaultRequestHeaders.Add("User-Agent", "IDS/ReleasePanel");
            _client.DefaultRequestHeaders.Add("Authorization", credentials.ToString());

            _organization = organization;
        }
        protected override ClientWebSocket CreateWebSocket()
        {
            ClientWebSocket webSocket = base.CreateWebSocket();

            AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Bearer", this.oauthAccessToken);

            webSocket.Options.SetRequestHeader("Authorization", authHeader.ToString());
            webSocket.Options.SetRequestHeader("X-Is-Bot", true.ToString());

            return(webSocket);
        }
예제 #16
0
        protected override ClientWebSocket CreateWebSocket()
        {
            ClientWebSocket webSocket = base.CreateWebSocket();

            AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Bearer", this.oauthAccessToken);

            webSocket.Options.SetRequestHeader("Authorization", authHeader.ToString());
            webSocket.Options.SetRequestHeader("X-Interactive-Version", this.InteractiveGame.versions.OrderByDescending(v => v.versionOrder).First().id.ToString());
            webSocket.Options.SetRequestHeader("X-Protocol-Version", "2.0");

            return(webSocket);
        }
 public static string GetTokenFromAuthorizationHeader(this AuthenticationHeaderValue header)
 {
     try
     {
         var tokenRaw = header.ToString();
         return(tokenRaw.ToLower().StartsWith("bearer ") ? tokenRaw.Substring(7) : tokenRaw);
     }
     catch
     {
         throw new ArgumentException("Problem getting user id from Auth Header");
     }
 }
예제 #18
0
        private string ConstructKeyBasedOnAuthorizationHeader(string mainKey, AuthenticationHeaderValue authHeader)
        {
            const string WithCredentials = nameof(WithCredentials);
            const string NoCredentials   = nameof(NoCredentials);

            if (authHeader != null && string.IsNullOrWhiteSpace(authHeader.ToString()) == false)
            {
                return(ConstructKey(mainKey, WithCredentials));
            }

            return(ConstructKey(mainKey, NoCredentials));
        }
예제 #19
0
        public static TResult GetClaimsFromAuthorizationHeader <TResult>(this AuthenticationHeaderValue header,
                                                                         Func <IEnumerable <Claim>, TResult> success,
                                                                         Func <TResult> authorizationNotSet,
                                                                         Func <string, TResult> failure,
                                                                         string issuerConfigSetting        = EastFive.Security.AppSettings.TokenIssuer,
                                                                         string validationKeyConfigSetting = EastFive.Security.AppSettings.TokenKey)
        {
            if (default(AuthenticationHeaderValue) == header)
            {
                return(authorizationNotSet());
            }
            var jwtString = header.ToString();

            return(jwtString.GetClaimsFromJwtToken(success, authorizationNotSet, failure, issuerConfigSetting, validationKeyConfigSetting));
        }
예제 #20
0
파일: Robot.cs 프로젝트: mp-iconsys/Mirage
    /// <summary>
    ///
    /// </summary>
    public void fetchConnectionDetails()
    {
        string apiUsername, apiPassword;

        if (resumingSession)
        {
            // We're resuming an existing session so fetch the robot connection details from a database
            string query        = "SELECT IP, AUTH FROM robot WHERE ROBOT_ID =" + id;
            var    getRobotData = new MySqlCommand(query, db);

            using (MySqlDataReader reader = getRobotData.ExecuteReader())
            {
                while (reader.Read())
                {
                    ipAddress = reader.GetString("IP");
                    authValue = new AuthenticationHeaderValue("Basic", reader.GetString("AUTH"));
                }
            }
        }
        else
        {
            // We've got a new session so input the details manually in the terminal
            // Firstm fetch the details

            Console.WriteLine("Please Enter The IP Address Of The Robot No " + id + ":");
            ipAddress = Console.ReadLine();
            // TODO: Check that the input is correct - length & type

            Console.WriteLine("Enter API Username:"******"Enter API Password:"******"username:"******"Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{apiUsername}:{ComputeSha256Hash(apiPassword)}")));

            logger(AREA, DEBUG, authValue.ToString());

            // Store the data in the DB
            //string query = "REPLACE INTO robot (`ROBOT_ID`, `IP`, `AUTH`) VALUES ('" + id + "', '" + ipAddress + "', '" + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{apiUsername}:{ComputeSha256Hash(apiPassword)}")) + "');";
            //Globals.issueInsertQuery(query);

            // Change the App.config setting so that we load an existing config next time
            //Globals.AddUpdateAppSettings("resumingSession", "true");
        }
    }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            HttpRequestMessage        request       = actionContext.Request;
            AuthenticationHeaderValue authorization = request.Headers.Authorization;

            if (actionContext.ActionDescriptor.GetCustomAttributes <SkipFilterAttribute>().Any())
            {
                return;
            }

            ActivityAuthorize activityAuthorize = actionContext
                                                  .ActionDescriptor.GetCustomAttributes <ActivityAuthorize>().SingleOrDefault();

            if (activityAuthorize == null || authorization == null)
            {
                actionContext.Response = request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                                                                     _personAppService.Localize("Unauthorized_Request_NoUser"));
                return;
            }

            string userAuthToken = authorization.ToString();
            // Authentication by validate user token
            ResponseMessageDTO tokenResponseMessageDto = _tokenAppService.ValidateToken(userAuthToken);

            if (!tokenResponseMessageDto.Status)
            {
                actionContext.Response = request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                                                                     tokenResponseMessageDto.Message);
                return;
            }
            else
            {
                string username = _tokenAppService.GetUsernameByToken(userAuthToken);

                if (string.IsNullOrEmpty(activityAuthorize.ActivityName))
                {
                    return;
                }
                ResponseMessageDTO authorizeActivityResponseMessageDto = _personAppService
                                                                         .CheckAuthorizeActivity(username, activityAuthorize.ActivityName);
                if (!authorizeActivityResponseMessageDto.Status)
                {
                    actionContext.Response = request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                                                                         authorizeActivityResponseMessageDto.Message);
                    return;
                }
            }
        }
예제 #22
0
        protected override ClientWebSocket CreateWebSocket()
        {
            ClientWebSocket webSocket = base.CreateWebSocket();

            AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Bearer", this.oauthAccessToken);

            webSocket.Options.SetRequestHeader("Authorization", authHeader.ToString());
            webSocket.Options.SetRequestHeader("X-Interactive-Version", this.Version.id.ToString());
            webSocket.Options.SetRequestHeader("X-Protocol-Version", "2.0");
            if (!string.IsNullOrEmpty(this.ShareCode))
            {
                webSocket.Options.SetRequestHeader("X-Interactive-Sharecode", this.ShareCode);
            }

            return(webSocket);
        }
예제 #23
0
        static void Main()
        {
            var authContext = new AuthenticationContext(Authority);
            var result      = authContext.AcquireToken(Resource, NativeClientId, new Uri(NativeClientRedirectUri));

            SampleContext context = new SampleContext(new Uri(ServiceAddress));

            context.SendingRequest2 += (sender, args) =>
            {
                var header = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                args.RequestMessage.SetHeader("Authorization", header.ToString());
            };
            var employees = context.Employees.ToArray();

            Console.WriteLine(employees.Length);
        }
예제 #24
0
        private static BasicCredentials ParseCredentials(AuthenticationHeaderValue authHeader)
        {
            try
            {
                var credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader.ToString().Substring(6))).Split(':');

                return(new BasicCredentials
                {
                    Username = credentials[0],
                    Password = credentials[1]
                });
            }
            catch { }

            return(new BasicCredentials());
        }
        private static BasicCredentials ParseCredentials(AuthenticationHeaderValue authHeader)
        {
            try
            {
                var credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader.ToString().Substring(6)));
                int splitOn     = credentials.IndexOf(':');

                return(new BasicCredentials
                {
                    Username = credentials.Substring(0, splitOn),
                    Password = credentials.Substring(splitOn + 1)
                });
            }
            catch { }

            return(new BasicCredentials());
        }
        public bool IsAuthorized(AuthenticationHeaderValue authorization, UserContract user)
        {
            if (authorization == null)
            {
                throw new ValidationException(System.Net.HttpStatusCode.Unauthorized, Resources.ApiResources.NotAuthorized);
            }

            var tokenExpired = (DateTime.UtcNow.TimeOfDay - user.LastLogin.Value.TimeOfDay).TotalMinutes > 30;

            if (tokenExpired)
            {
                throw new ValidationException(System.Net.HttpStatusCode.Unauthorized, ApiResources.SessionExpired);
            }

            var requestAuthorizationToken = authorization.ToString().Replace(tokenPrefix, "").Trim();

            return(string.Equals(requestAuthorizationToken, user.AccessToken));
        }
        /// <summary>
        /// <example>POST https://{instance}/DefaultCollection/[{project}/]_apis/wit/wiql?api-version={version}</example>
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Post(string url, string data)
        {
            try
            {
                using (var client = new WebClient())
                {
                    var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{accessToken}"));
                    var authHeader  = new AuthenticationHeaderValue("Basic", credentials);

                    client.Headers.Add(HttpRequestHeader.Authorization, authHeader.ToString());
                    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                    client.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-8");

                    return(client.UploadString(url, data));
                }
            }
            catch (Exception ex) {
                throw;
            }
        }
예제 #28
0
        public HttpResponseMessage Post(LogOnModel model)
        {
            try
            {
                if (Membership.ValidateUser(model.Email, model.Password) == false)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member doesn't exist"));
                }

                byte[] buffer = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", model.Email, model.Password));

                AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));

                return(Request.CreateResponse(HttpStatusCode.OK, new AuthorizationTicket {
                    Ticket = authHeader.ToString()
                }));
            }
            catch (Exception exc)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, exc.Message));
            }
        }
예제 #29
0
        public static AdalResponse CallGraph(string uri, dynamic postContent = null, bool isUpdate = false, string graphResource = null)
        {
            string resource = (graphResource != null) ? graphResource : Settings.GraphResource;

            var res = new AdalResponse
            {
                Successful = true
            };
            HttpResponseMessage response = null;

            try
            {
                AuthenticationResult authResult = null;

                // Get auth token
                var task = Task.Run(async() => {
                    authResult = await AuthenticateApp(resource);
                });
                task.Wait();

                string accessToken = authResult.AccessToken;

                var bearer = new AuthenticationHeaderValue("Bearer", accessToken);

                //getting inconsistent results (chunked vs not chunked) with async calls - switching to webclient/sync
                if (postContent != null)
                {
                    using (var httpClient = new HttpClient())
                    {
                        httpClient.Timeout = TimeSpan.FromSeconds(300);
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                        httpClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString());
                        httpClient.DefaultRequestHeaders.GetValues("client-request-id").Single();
                        string serialized = JsonConvert.SerializeObject(postContent);

                        HttpContent content = new StringContent(serialized, Encoding.UTF8, "application/json");

                        if (isUpdate)
                        {
                            var method  = new HttpMethod("PATCH");
                            var request = new HttpRequestMessage(method, uri)
                            {
                                Content = content
                            };

                            response = httpClient.SendAsync(request).Result;
                        }
                        else
                        {
                            response = httpClient.PostAsync(uri, content).Result;
                        }
                        res.ResponseContent = response.Content.ReadAsStringAsync().Result;
                        res.StatusCode      = response.StatusCode;
                        res.Message         = response.ReasonPhrase;
                        if (!response.IsSuccessStatusCode)
                        {
                            res.Successful = false;
                            var serverError        = JsonConvert.DeserializeObject <GraphError>(res.ResponseContent);
                            var reason             = (response == null ? "N/A" : response.ReasonPhrase);
                            var serverErrorMessage = (serverError.Error == null) ? "N/A" : serverError.Error.Message;
                            res.Message = string.Format("Server response: {0}. Server detail: {1})", reason, serverErrorMessage);
                            return(res);
                        }
                    }
                }
                else
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.Headers.Add("Authorization", bearer.ToString());
                        webClient.Headers.Add("client-request-id", Guid.NewGuid().ToString());

                        res.ResponseContent = webClient.DownloadString(uri);
                    }
                }
                return(res);
            }
            catch (Exception ex)
            {
                res.Successful = false;
                res.Message    = ex.Message;
                return(res);
            }
        }
        /// <summary>
        /// Authenticate async.
        /// This method:
        ///     - checks that there is an authorization field
        ///     - checks that if the authorization scheme is Anon the controller called is labelled with the Allow Anonymous attribute
        ///     - dispatches the authorization parameter to the appropriate auth manager
        ///     - populates the HTTP context with the user and app principals
        /// </summary>
        /// <remarks>
        /// Requirements for different schemes:
        ///  - SocialPlus: must include token
        ///  - Anon: must include app key
        ///  - OAuth: must include app key and token
        ///  - AADS2S: must include app key and token (and optionally user handle)
        /// In summary: the app key cannot be null unless AuthScheme is SocialPlus; token cannot be null unless AuthScheme is Anon
        /// </remarks>
        /// <param name="context">Http context</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Authenticate async task</returns>
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            HttpActionContext  actionContext = context.ActionContext;
            HttpRequestMessage request       = context.Request;
            int versionMajor             = 0;
            int versionMinor             = 0;
            List <IPrincipal> principals = null;

            // parse out the api version number from the request url
            try
            {
                UrlParser.GetMajorMinorAPIVersion(request.RequestUri, out versionMajor, out versionMinor);
            }
            catch (Exception e)
            {
                string errorMessage = "Request API version is malformed.";
                this.log.LogError(errorMessage, e);

                context.ErrorResult = new BadRequestMessageResult(ResponseStrings.VersionNumbersMalformed, request);
                return;
            }

            AuthenticationHeaderValue authorization = request.Headers.Authorization;

            if (authorization == null)
            {
                string errorMessage = "No authorization header field present.";
                this.log.LogError(errorMessage);

                context.ErrorResult = new UnauthorizedMessageResult(ResponseStrings.GenericUnauthorizedError, context.Request);
                return;
            }

            // Anon authorization is only allowed on controllers labelled with the AllowAnonymous attribute
            if (authorization.Scheme == AnonScheme && (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any() == false))
            {
                string errorMessage = $"Anon auth attempted on a controller/action not labelled AllowAnonymous. Auth: {authorization.ToString()}";
                this.log.LogError(errorMessage);

                context.ErrorResult = new UnauthorizedMessageResult(ResponseStrings.GenericUnauthorizedError, context.Request);
                return;
            }

            // Validate the authorization string
            try
            {
                principals = await this.authManager.ValidateAuth(authorization.Parameter, authorization.Scheme);
            }
            catch (Exception e)
            {
                // Catch unauthorized exceptions, log them, and return unauthorized
                string errorMessage = $"Invalid authorization header: {authorization.ToString()}";
                this.log.LogError(errorMessage, e);

                context.ErrorResult = new UnauthorizedMessageResult(ResponseStrings.GenericUnauthorizedError, context.Request);
                return;
            }

            // Save user and app principal in the HTTP context
            foreach (var p in principals)
            {
                if (p is AppPrincipal)
                {
                    HttpContext.Current.Items["AppPrincipal"] = p;
                }
                else if (p is UserPrincipal)
                {
                    HttpContext.Current.User = p;
                }
            }
        }