Exemplo n.º 1
0
        public virtual AuthorizeOrError TryAuthorize(string authorization, string url, RouteHandler route)
        {
            if (authorization == null)
                return AuthorizeOrError.Unauthorized("Authorization header not provided.", true);

            var splt = authorization.Split(' ');
            var authType = splt[0];
            if (splt.Length != 2)
                return AuthorizeOrError.Unauthorized("Invalid authorization header.", false);

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
            if (cred.Length != 2)
                return AuthorizeOrError.Unauthorized("Invalid authorization header content.", false);

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
                return AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized);

            var isAuthenticated = authType == "Hash"
                ? HashAuthentication.IsAuthenticated(user, Convert.FromBase64String(cred[1]))
                : PassAuthentication.IsAuthenticated(user, cred[1]);

            var identity = new RestIdentity(authType, isAuthenticated, user);
            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(url)
                    || PublicTemplate.Contains(route.Template)))
                    return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
                return AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden);
            }
            return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
        }
Exemplo n.º 2
0
        public virtual AuthorizeOrError TryAuthorize(HttpListenerContext context, RouteHandler route)
        {
            var request = context.Request;
            var authorization = request.Headers["Authorization"] ?? DefaultAuthorization;
            if (authorization == null)
            {
                context.Response.AddHeader("WWW-Authenticate", MissingBasicAuth);
                return AuthorizeOrError.Fail("Authorization header not provided.", HttpStatusCode.Unauthorized);
            }

            var splt = authorization.Split(' ');
            var authType = splt[0];
            if (splt.Length != 2)
                return AuthorizeOrError.Fail("Invalid authorization header.", HttpStatusCode.Unauthorized);

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
            if (cred.Length != 2)
                return AuthorizeOrError.Fail("Invalid authorization header content.", HttpStatusCode.Unauthorized);

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
                return AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized);

            var identity = new RestIdentity(authType, Authentication.IsAuthenticated(user, cred[1]), user);
            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(request.RawUrl)
                    || PublicTemplate.Contains(route.Template)))
                    return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
                return AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden);
            }
            return AuthorizeOrError.Success(PrincipalFactory.Create(identity));
        }
Exemplo n.º 3
0
        public async Task <RestResponse> RestAsync(RestIdentity identity, RestRequest request)
        {
            try
            {
                RestResponse response = await RestCaller.SendAsync(identity, request).Free();

                return(response);
            }
            catch (Exception ex) when(!(ex is OfflineApiException))
            {
                throw new ApiException(string.Format(CultureInfo.InvariantCulture, "{2} {1} {0}", request.Url, request.Method, ex.Message), ex);
            }
        }
Exemplo n.º 4
0
        public async Task <RestResponse> SendAsync(RestIdentity identity, RestRequest request)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (!New <IInternetState>().Connected)
            {
                throw new OfflineApiException(ExceptionMessage("Internet Unavailable", request));
            }

            try
            {
                switch (request.Method)
                {
                case "GET":
                    if (request.Content.Text.Length > 0)
                    {
                        throw new ArgumentException("You can't send content with a GET request.", "request");
                    }
                    return(await SendGetAsync(identity, request).Free());

                case "PUT":
                    return(await SendPutAsync(identity, request).Free());

                case "POST":
                    return(await SendPostAsync(identity, request).Free());

                default:
                    throw new NotSupportedException("The method '{0}' is not supported.".InvariantFormat(request.Method));
                }
            }
            catch (TaskCanceledException tcex)
            {
                throw new OfflineApiException(ExceptionMessage("Offline", request), tcex);
            }
            catch (WebException wex)
            {
                throw new OfflineApiException(ExceptionMessage("Offline", request), wex);
            }
            catch (HttpRequestException hrex)
            {
                New <IInternetState>().Clear();
                throw new OfflineApiException(ExceptionMessage("Offline", request), hrex);
            }
        }
Exemplo n.º 5
0
        public virtual AuthorizeOrError TryAuthorize(HttpListenerContext context, RouteHandler route)
        {
            var request       = context.Request;
            var authorization = request.Headers["Authorization"] ?? DefaultAuthorization;

            if (authorization == null)
            {
                context.Response.AddHeader("WWW-Authenticate", MissingBasicAuth);
                return(AuthorizeOrError.Fail("Authorization header not provided.", HttpStatusCode.Unauthorized));
            }

            var splt     = authorization.Split(' ');
            var authType = splt[0];

            if (splt.Length != 2)
            {
                return(AuthorizeOrError.Fail("Invalid authorization header.", HttpStatusCode.Unauthorized));
            }

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');

            if (cred.Length != 2)
            {
                return(AuthorizeOrError.Fail("Invalid authorization header content.", HttpStatusCode.Unauthorized));
            }

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
            {
                return(AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized));
            }

            var isAuthenticated = authType == "Hash"
                                ? HashAuthentication.IsAuthenticated(user, Convert.FromBase64String(cred[1]))
                                : PassAuthentication.IsAuthenticated(user, cred[1]);

            var identity = new RestIdentity(authType, isAuthenticated, user);

            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(request.RawUrl) ||
                     PublicTemplate.Contains(route.Template)))
                {
                    return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
                }
                return(AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden));
            }
            return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
        }
Exemplo n.º 6
0
        private async static Task <RestResponse> SendPostAsync(RestIdentity identity, RestRequest request)
        {
            string content = String.Empty;

            using (HttpClient client = CreateHttpClient())
            {
                PrepareClient(client, identity, request);

                StringContent       httpContent  = new StringContent(request.Content.Text, Encoding.UTF8, "application/json");
                HttpResponseMessage httpResponse = await client.PostAsync(request.Url.PathAndQuery, httpContent).Free();

                content = await httpResponse.Content.ReadAsStringAsync().Free();

                return(new RestResponse(httpResponse.StatusCode, content));
            }
        }
Exemplo n.º 7
0
        public virtual AuthorizeOrError TryAuthorize(string authorization, string url, RouteHandler route)
        {
            if (authorization == null)
            {
                return(AuthorizeOrError.Unauthorized("Authorization header not provided.", true));
            }

            var splt     = authorization.Split(' ');
            var authType = splt[0];

            if (splt.Length != 2)
            {
                return(AuthorizeOrError.Unauthorized("Invalid authorization header.", false));
            }

            var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');

            if (cred.Length != 2)
            {
                return(AuthorizeOrError.Unauthorized("Invalid authorization header content.", false));
            }

            var user = cred[0];

            if (string.IsNullOrEmpty(user))
            {
                return(AuthorizeOrError.Fail("User not specified in authorization header.", HttpStatusCode.Unauthorized));
            }

            var isAuthenticated = authType == "Hash"
                                ? HashAuthentication.IsAuthenticated(user, Convert.FromBase64String(cred[1]))
                                : PassAuthentication.IsAuthenticated(user, cred[1]);

            var identity = new RestIdentity(authType, isAuthenticated, user);

            if (!identity.IsAuthenticated)
            {
                if ((PublicUrl.Contains(url) ||
                     PublicTemplate.Contains(route.Template)))
                {
                    return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
                }
                return(AuthorizeOrError.Fail("User {0} was not authenticated.".With(user), HttpStatusCode.Forbidden));
            }
            return(AuthorizeOrError.Success(PrincipalFactory.Create(identity)));
        }
Exemplo n.º 8
0
        private static void PrepareClient(HttpClient client, RestIdentity identity, RestRequest request)
        {
            client.BaseAddress = new Uri(request.Url.GetLeftPart(UriPartial.Authority));
            client.Timeout     = request.Timeout > TimeSpan.Zero ? request.Timeout : TimeSpan.FromMilliseconds(-1);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            foreach (string key in request.Headers.Collection.Keys)
            {
                client.DefaultRequestHeaders.Add(key, request.Headers.Collection[key]);
            }

            if (identity.User.Length > 0)
            {
                string credentials = "{0}:{1}".InvariantFormat(identity.User, identity.Password.ToUtf8Base64());
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials)));
            }
        }
        private IIdentity GetClientIdentity(EvaluationContext evaluationContext)
        {
            object obj;
            if (!evaluationContext.Properties.TryGetValue("Identities", out obj))
            {
                var authorization = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authorization];
                if (authorization == null)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["WWW-Authenticate"] = "Basic realm=\"site\"";
                    throw new Exception("Authorization header not provided.");
                }

                var splt = authorization.Split(' ');
                var authType = splt[0];
                if (splt.Length != 2)
                    throw new Exception("Invalid authorization header.");

                var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
                if (cred.Length != 2)
                    throw new Exception("Invalid authorization header content.");

                var user = cred[0];

                if (string.IsNullOrEmpty(user))
                    throw new Exception("User not specified in authorization header.");

                var identity = new RestIdentity
                {
                    AuthenticationType = authType,
                    IsAuthenticated = Authentication.IsAuthenticated(user, cred[1]),
                    Name = user
                };
                if (!identity.IsAuthenticated)
                    throw new Exception("User " + user + " is not allowed");
                return identity;
            }

            var identities = obj as IList<IIdentity>;
            if (identities == null || identities.Count < 1)
                throw new Exception("No Identity found");

            return identities[0];
        }
Exemplo n.º 10
0
        private async static Task <RestResponse> SendGetAsync(RestIdentity identity, RestRequest request)
        {
            string content = String.Empty;

            using (HttpClient client = CreateHttpClient())
            {
                PrepareClient(client, identity, request);

                HttpResponseMessage httpResponse = await client.GetAsync(request.Url.PathAndQuery).Free();

                content = await httpResponse.Content.ReadAsStringAsync().Free();

                if (content.Length > 0 && httpResponse.Content?.Headers?.ContentType?.MediaType != "application/json")
                {
                    throw new HttpRequestException("Expected Media Type 'application/json'.");
                }

                return(new RestResponse(httpResponse.StatusCode, content));
            }
        }
        public async Task TestAnonymousSummary()
        {
            RestIdentity identity = new RestIdentity();

            UserAccount summary = new UserAccount(identity.User, SubscriptionLevel.Free, DateTime.UtcNow.AddMonths(1), AccountStatus.Verified, Offers.None, new AccountKey[] { new AccountKey("*****@*****.**", Convert.ToBase64String(new byte[16]), new KeyPair("public-key-fake-PEM", String.Empty), DateTime.MinValue, PrivateKeyStatus.PassphraseKnown), });
            string      content = Resolve.Serializer.Serialize(summary);

            Mock <IRestCaller> mockRestCaller = new Mock <IRestCaller>();

            mockRestCaller.Setup <Task <RestResponse> >(wc => wc.SendAsync(It.Is <RestIdentity>((i) => i.User.Length == 0), It.Is <RestRequest>((r) => r.Url == new Uri("http://localhost/api/users/all/accounts/[email protected]")))).Returns(() => Task.FromResult(new RestResponse(HttpStatusCode.OK, content)));
            mockRestCaller.Setup <string>(wc => wc.UrlEncode(It.IsAny <string>())).Returns <string>((url) => WebUtility.UrlEncode(url));
            TypeMap.Register.New <IRestCaller>(() => mockRestCaller.Object);

            AxCryptApiClient client      = new AxCryptApiClient(identity, new Uri("http://localhost/api/"), TimeSpan.Zero);
            UserAccount      userSummary = await client.GetAllAccountsUserAccountAsync("*****@*****.**");

            Assert.That(userSummary.UserName, Is.EqualTo(identity.User));
            Assert.That(userSummary.AccountKeys.Count(), Is.EqualTo(1), "There should be an AccountKey here.");
            Assert.That(userSummary.AccountKeys.First(), Is.EqualTo(summary.AccountKeys.First()));
        }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AxCryptApiClient"/> class.
 /// </summary>
 /// <param name="identity">The identity on whos behalf to make the call.</param>
 public AxCryptApiClient(RestIdentity identity, Uri baseUrl, TimeSpan timeout)
 {
     Identity = identity;
     BaseUrl  = baseUrl;
     Timeout  = timeout;
 }
Exemplo n.º 13
0
        public async Task <RestResponse> SendAsync(RestIdentity identity, RestRequest request)
        {
            await Task.Run(() => OnCalling());

            return(_result);
        }
Exemplo n.º 14
0
        private IIdentity GetClientIdentity(EvaluationContext evaluationContext)
        {
            object obj;

            if (!evaluationContext.Properties.TryGetValue("Identities", out obj))
            {
                var authorization = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authorization] ?? DefaultAuthorization;
                if (authorization == null)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["WWW-Authenticate"] = "Basic realm=\"site\"";
                    Utility.ThrowError("Authorization header not provided.", HttpStatusCode.Unauthorized);
                }

                var splt     = authorization.Split(' ');
                var authType = splt[0];
                if (splt.Length != 2)
                {
                    Utility.ThrowError("Invalid authorization header.", HttpStatusCode.Unauthorized);
                }

                var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
                if (cred.Length != 2)
                {
                    Utility.ThrowError("Invalid authorization header content.", HttpStatusCode.Unauthorized);
                }

                var user     = cred[0];
                var password = new SecureString();
                foreach (var c in cred[1])
                {
                    password.AppendChar(c);
                }

                if (string.IsNullOrEmpty(user))
                {
                    Utility.ThrowError("User not specified in authorization header.", HttpStatusCode.Unauthorized);
                }

                var identity = new RestIdentity
                {
                    AuthenticationType = authType,
                    IsAuthenticated    = Authentication.IsAuthenticated(user, password),
                    Name = user
                };
                var template = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;
                if (!identity.IsAuthenticated)
                {
                    Utility.ThrowError("User '" + user + "' was not authenticated.", HttpStatusCode.Forbidden);
                }
                else if (template == null)
                {
                    var url = OperationContext.Current.RequestContext.RequestMessage.Headers.To;
                    Utility.ThrowError("Unknown route: " + url.PathAndQuery, HttpStatusCode.NotFound);
                }
                return(identity);
            }

            var identities = obj as IList <IIdentity>;

            if (identities == null || identities.Count < 1)
            {
                Utility.ThrowError("No Identity found.", HttpStatusCode.Unauthorized);
            }

            return(identities[0]);
        }
Exemplo n.º 15
0
        private IIdentity GetClientIdentity(EvaluationContext evaluationContext)
        {
            object obj;
            if (!evaluationContext.Properties.TryGetValue("Identities", out obj))
            {
                var authorization = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authorization] ?? DefaultAuthorization;
                if (authorization == null)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["WWW-Authenticate"] = "Basic realm=\"site\"";
                    Utility.ThrowError("Authorization header not provided.", HttpStatusCode.Unauthorized);
                }

                var splt = authorization.Split(' ');
                var authType = splt[0];
                if (splt.Length != 2)
                    Utility.ThrowError("Invalid authorization header.", HttpStatusCode.Unauthorized);

                var cred = Encoding.UTF8.GetString(Convert.FromBase64String(splt[1])).Split(':');
                if (cred.Length != 2)
                    Utility.ThrowError("Invalid authorization header content.", HttpStatusCode.Unauthorized);

                var user = cred[0];
                var password = new SecureString();
                foreach (var c in cred[1])
                    password.AppendChar(c);

                if (string.IsNullOrEmpty(user))
                    Utility.ThrowError("User not specified in authorization header.", HttpStatusCode.Unauthorized);

                var identity = new RestIdentity
                {
                    AuthenticationType = authType,
                    IsAuthenticated = Authentication.IsAuthenticated(user, password),
                    Name = user
                };
                var template = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;
                if (!identity.IsAuthenticated)
                {
                    Utility.ThrowError("User '" + user + "' was not authenticated.", HttpStatusCode.Forbidden);
                }
                else if (template == null)
                {
                    var url = OperationContext.Current.RequestContext.RequestMessage.Headers.To;
                    Utility.ThrowError("Unknown route: " + url.PathAndQuery, HttpStatusCode.NotFound);
                }
                return identity;
            }

            var identities = obj as IList<IIdentity>;
            if (identities == null || identities.Count < 1)
                Utility.ThrowError("No Identity found.", HttpStatusCode.Unauthorized);

            return identities[0];
        }