Exemplo n.º 1
0
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            var authHeader = request.Headers.Authorization;
            string scheme = authHeader != null ? authHeader.Scheme.ToLower() : null;
            string token = null;
            if (authHeader != null && (scheme == BearerScheme || scheme == TokenScheme)) {
                token = authHeader.Parameter;
            } else if (authHeader != null && scheme == BasicScheme) {
                var authInfo = request.GetBasicAuth();
                if (authInfo != null) {
                    if (authInfo.Username.ToLower() == "client")
                        token = authInfo.Password;
                    else if (authInfo.Password.ToLower() == "x-oauth-basic" || String.IsNullOrEmpty(authInfo.Password))
                        token = authInfo.Username;
                    else {
                        User user;
                        try {
                            user = _userRepository.GetByEmailAddress(authInfo.Username);
                        } catch (Exception) {
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                        }

                        if (user == null || !user.IsActive)
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                        if (String.IsNullOrEmpty(user.Salt))
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                        string encodedPassword = authInfo.Password.ToSaltedHash(user.Salt);
                        if (!String.Equals(encodedPassword, user.Password))
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                        request.GetRequestContext().Principal = new ClaimsPrincipal(user.ToIdentity());
                        return await base.SendAsync(request, cancellationToken);
                    }
                }
            } else {
                string queryToken = request.GetQueryString("access_token");
                if (!String.IsNullOrEmpty(queryToken))
                    token = queryToken;

                queryToken = request.GetQueryString("api_key");
                if (String.IsNullOrEmpty(token) && !String.IsNullOrEmpty(queryToken))
                    token = queryToken;

                queryToken = request.GetQueryString("apikey");
                if (String.IsNullOrEmpty(token) && !String.IsNullOrEmpty(queryToken))
                    token = queryToken;

            }

            if (!String.IsNullOrEmpty(token)) {
                IPrincipal principal = _tokenManager.Validate(token);
                if (principal != null)
                    request.GetRequestContext().Principal = principal;
            }

            return await base.SendAsync(request, cancellationToken);
        }
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (request != null)
            {
                var traceQueryString = request.GetQueryString("trace"); ;

                bool shouldTrace;
                if (traceQueryString != null &&  Boolean.TryParse(traceQueryString, out shouldTrace)&& shouldTrace)
            {
                    object perRequestTrace;
                    if (!request.Properties.TryGetValue("perRequestTrace", out perRequestTrace))
                    {
                        perRequestTrace = new List<string>();
                        request.Properties["perRequestTrace"] = perRequestTrace;
                    }

                    var record = new TraceRecord(request, category, level);
                    traceAction(record);
                    (perRequestTrace as List<string>).Add(Log(record));
                }
            }

            if (_innerWriter != null)
            {
                _innerWriter.Trace(request, category, level, traceAction);
            }
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            var authHeader = request.Headers.Authorization;
            string token = null;
            if (authHeader != null && (authHeader.Scheme == BearerScheme || authHeader.Scheme == TokenScheme))
                token = authHeader.Parameter;
            else if (authHeader != null && authHeader.Scheme == BasicScheme) {
                string text = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter));
                int delimiterIndex = text.IndexOf(':');
                if (delimiterIndex >= 0 && String.Equals("client", text.Substring(0, delimiterIndex), StringComparison.OrdinalIgnoreCase))
                    token = text.Substring(delimiterIndex + 1);
            } else {
                token = request.GetQueryString("access_token");
            }

            if (String.IsNullOrEmpty(token))
                return BaseSendAsync(request, cancellationToken);

            //try {
            IPrincipal principal = _tokenManager.Validate(token);
            if (principal != null)
                request.GetRequestContext().Principal = principal;
            
            //} catch (SecurityTokenExpiredException e) {
            //    _logger.ErrorFormat("Security token expired: {0}", e);

            //    var response = new HttpResponseMessage((HttpStatusCode)440) {
            //        Content = new StringContent("Security token expired exception")
            //    };

            //    var tsc = new TaskCompletionSource<HttpResponseMessage>();
            //    tsc.SetResult(response);
            //    return tsc.Task;
            //} catch (SecurityTokenSignatureKeyNotFoundException e) {
            //    _logger.ErrorFormat("Error during JWT validation: {0}", e);

            //    var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) {
            //        Content = new StringContent("Untrusted signing cert")
            //    };

            //    var tsc = new TaskCompletionSource<HttpResponseMessage>();
            //    tsc.SetResult(response);
            //    return tsc.Task;
            //} catch (SecurityTokenValidationException e) {
            //    _logger.ErrorFormat("Error during JWT validation: {0}", e);
            //    throw;
            //} catch (Exception e) {
            //    _logger.ErrorFormat("Error during JWT validation: {0}", e);
            //    throw;
            //}

            return BaseSendAsync(request, cancellationToken);
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var apikey = request.GetQueryString("apikey");

            if (!string.IsNullOrWhiteSpace(apikey))
            {
                Repository.Log.Add(string.Format("{0} {1} {2}", apikey, request.Method, request.RequestUri));
                var result = await base.SendAsync(request, cancellationToken);
                Repository.Log.Add(string.Format("{0} {1}", apikey, result.StatusCode));
                
                return result;
            }

            return await base.SendAsync(request, cancellationToken);
        }
Exemplo n.º 5
0
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            var authHeader = request.Headers.Authorization;
            string scheme = authHeader?.Scheme.ToLower();
            string token = null;
            if (authHeader != null && (scheme == BearerScheme || scheme == TokenScheme)) {
                token = authHeader.Parameter;
            } else if (authHeader != null && scheme == BasicScheme) {
                var authInfo = request.GetBasicAuth();
                if (authInfo != null) {
                    if (authInfo.Username.ToLower() == "client")
                        token = authInfo.Password;
                    else if (authInfo.Password.ToLower() == "x-oauth-basic" || String.IsNullOrEmpty(authInfo.Password))
                        token = authInfo.Username;
                    else {
                        User user;
                        try {
                            user = await _userRepository.GetByEmailAddressAsync(authInfo.Username);
                        } catch (Exception) {
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                        }

                        if (user == null || !user.IsActive)
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                        if (String.IsNullOrEmpty(user.Salt))
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                        string encodedPassword = authInfo.Password.ToSaltedHash(user.Salt);
                        if (!String.Equals(encodedPassword, user.Password))
                            return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                        SetupUserRequest(request, user);
                        return await BaseSendAsync(request, cancellationToken);
                    }
                }
            } else {
                token = request.GetQueryString("access_token");
                if (String.IsNullOrEmpty(token))
                    token  = request.GetQueryString("api_key");

                if (String.IsNullOrEmpty(token))
                    token = request.GetQueryString("apikey");
            }

            if (String.IsNullOrEmpty(token))
                return await BaseSendAsync(request, cancellationToken);

            var tokenRecord = await _tokenRepository.GetByIdAsync(token, true);
            if (tokenRecord == null)
                return new HttpResponseMessage(HttpStatusCode.Unauthorized);

            if (tokenRecord.ExpiresUtc.HasValue && tokenRecord.ExpiresUtc.Value < DateTime.UtcNow)
                return new HttpResponseMessage(HttpStatusCode.Unauthorized);

            if (!String.IsNullOrEmpty(tokenRecord.UserId)) {
                var user = await _userRepository.GetByIdAsync(tokenRecord.UserId, true);
                if (user == null)
                    return new HttpResponseMessage(HttpStatusCode.Unauthorized);

                SetupUserRequest(request, user);
            } else {
                SetupTokenRequest(request, tokenRecord);
            }

            return await BaseSendAsync(request, cancellationToken);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Retrieves the Jsonp Callback function
        /// from the query string
        /// </summary>
        /// <returns></returns>
        private string GetJsonCallbackFunction(HttpRequestMessage request)
        {
            if (request.Method != HttpMethod.Get)
                return null;

            var queryVal = request.GetQueryString(this.JsonpParameterName);
            //var query = HttpUtility.ParseQueryString(request.RequestUri.Query);
            //var queryVal = query[this.JsonpParameterName];

            if (string.IsNullOrEmpty(queryVal))
                return null;

            return queryVal;
        }