Exemplo n.º 1
0
        public void Shall_parse_header()
        {
            const string str =
                "Basic username=\"a\", realm=\"b\", nonce=\"c\", uri=\"d\", response=\"e\", digest=\"f\", " +
                "algorithm=\"g\", cnonce=\"h\", opaque=\"i\", qop=\"j\", nc=00000001, version=\"k\", " +
                "targetname=\"l\", gssapi-data=\"m\", crand=\"n\", cnum=\"o\"";

            Assert.That(AuthorizationHeader.TryParse(str, out AuthorizationHeader header), Is.True);
            Assert.That(header.AuthenticationType, Is.EqualTo("Basic"));
            Assert.That(header.Username, Is.EqualTo("\"a\""));
            Assert.That(header.Realm, Is.EqualTo("\"b\""));
            Assert.That(header.Nonce, Is.EqualTo("\"c\""));
            Assert.That(header.Uri, Is.EqualTo("\"d\""));
            Assert.That(header.Response, Is.EqualTo("\"e\""));
            Assert.That(header.Digest, Is.EqualTo("\"f\""));
            Assert.That(header.Algorithm, Is.EqualTo("\"g\""));
            Assert.That(header.CNonce, Is.EqualTo("\"h\""));
            Assert.That(header.Opaque, Is.EqualTo("\"i\""));
            Assert.That(header.MessageQop, Is.EqualTo("\"j\""));
            Assert.That(header.NonceCount, Is.EqualTo("00000001"));
            Assert.That(header.Version, Is.EqualTo("\"k\""));
            Assert.That(header.TargetName, Is.EqualTo("\"l\""));
            Assert.That(header.GssApiData, Is.EqualTo("\"m\""));
            Assert.That(header.CRand, Is.EqualTo("\"n\""));
            Assert.That(header.CNum, Is.EqualTo("\"o\""));
        }
Exemplo n.º 2
0
        private AuthorizationHeader GenerateAuthorizationHeader(Nonce nonce, TimeStamp timestamp, Signature signature)
        {
            AuthorizationHeader header = new AuthorizationHeader(credentials, nonce, timestamp, signature);

            header.Token = token;
            return(header);
        }
Exemplo n.º 3
0
        /// <summary>
        /// An authentication response have been received from the web browser.
        /// Check if it's correct
        /// </summary>
        /// <param name="header">Authorization header</param>
        /// <param name="realm">Realm that should be authenticated</param>
        /// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param>
        /// <param name="options">Not used in basic auth</param>
        /// <returns>Authentication object that is stored for the request. A user class or something like that.</returns>
        /// <exception cref="ArgumentException">if authenticationHeader is invalid</exception>
        /// <exception cref="ArgumentNullException">If any of the paramters is empty or null.</exception>
        public bool Authenticate(AuthorizationHeader header, string realm, string httpVerb, object[] options)
        {
            if (header == null)
            {
                throw new ArgumentNullException("realm");
            }
            if (string.IsNullOrEmpty(realm))
            {
                throw new ArgumentNullException("realm");
            }
            if (string.IsNullOrEmpty(httpVerb))
            {
                throw new ArgumentNullException("httpVerb");
            }

            /*
             * To receive authorization, the client sends the userid and password,
             *  separated by a single colon (":") character, within a base64 [7]
             *  encoded string in the credentials.*/
            string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(header.Data));
            int    pos     = decoded.IndexOf(':');

            if (pos == -1)
            {
                return(false);
            }

            string password = decoded.Substring(pos + 1, decoded.Length - pos - 1);
            string userName = decoded.Substring(0, pos);
            var    context  = new BasicAuthenticationContext(realm, userName, password);

            return(_handler(context));
        }
Exemplo n.º 4
0
        public void Shall_stringify_header()
        {
            var header = new AuthorizationHeader
            {
                AuthenticationType = "Basic",
                Username           = "******"a\"",
                Realm      = "\"b\"",
                Nonce      = "\"c\"",
                Uri        = "\"d\"",
                Response   = "\"e\"",
                Digest     = "\"f\"",
                Algorithm  = "\"g\"",
                CNonce     = "\"h\"",
                Opaque     = "\"i\"",
                MessageQop = "\"j\"",
                NonceCount = "00000001",
                Version    = "\"k\"",
                TargetName = "\"l\"",
                GssApiData = "\"m\"",
                CRand      = "\"n\"",
                CNum       = "\"o\""
            };

            Assert.That(
                header.ToString(),
                Is.EqualTo(
                    "Basic username=\"a\", realm=\"b\", nonce=\"c\", uri=\"d\", response=\"e\", digest=\"f\", " +
                    "algorithm=\"g\", cnonce=\"h\", opaque=\"i\", qop=\"j\", nc=00000001, version=\"k\", " +
                    "targetname=\"l\", gssapi-data=\"m\", crand=\"n\", cnum=\"o\""));
        }
        public NegotiationToken GetToken()
        {
            WebRequest request = WebRequest.Create(requestUri);

            request.Method = "POST";

            Nonce     nonce     = Nonce.Generate();
            TimeStamp timestamp = TimeStamp.Generate();

            BaseString baseString = new BaseString(request.RequestUri,
                                                   request.Method, nonce, timestamp, credentials, HmacSha1Signature.MethodName);

            Signature signature = new HmacSha1Signature(baseString.ToString(), credentials);

            AuthorizationHeader header = new AuthorizationHeader(credentials, nonce, timestamp, signature);

            request.Headers.Add(HttpRequestHeader.Authorization, header.ToString());

            using (WebResponse res = request.GetResponse())
                using (Stream s = res.GetResponseStream())
                    using (StreamReader sr = new StreamReader(s))
                    {
                        NameValueCollection response = HttpUtility.ParseQueryString(sr.ReadToEnd());
                        return(new NegotiationToken(response["oauth_token"], response["oauth_token_secret"]));
                    }
        }
        static void Main(string[] args)
        {
            // http://www.compilemode.com/2016/03/calling-web-service-using-soap-request-without-wsdl-and-endpoints.html
            // https://victorz.ru/20180805729
            OperationHistory12  operation     = new OperationHistory12();
            AuthorizationHeader authorization = new AuthorizationHeader
            {
                mustUnderstand = "1",
                login          = "******",
                password       = "******"
            };
            OperationHistoryRequest request = new OperationHistoryRequest
            {
                MessageType = 0,
                Barcode     = "22221312123123"
            };
            var res = operation.getOperationHistory(
                request
                , authorization
                );


            Console.Write(res.ToString());
            Console.ReadKey();
        }
Exemplo n.º 7
0
        public async Task UpdateUserAsync(UserUpdate userUpdate)
        {
            string url = string.Format("{0}/{1}", URL.RESTRoot, "user");

            string authzHeader = AuthorizationHeader.CreateForREST(Config.ConsumerKey, Config.ConsumerSecret, AuthToken.Token, AuthToken.TokenSecret, url, "PUT");

            string serializeObject = JsonConvert.SerializeObject(userUpdate);

            HttpContent httpContent = new StringContent(serializeObject);

            HttpRequestItem httpRequestItem = new HttpRequestItem()
            {
                URL           = url,
                HttpMethod    = HttpMethod.Put,
                AuthzHeader   = authzHeader,
                HttpContent   = httpContent,
                IsDataRequest = true
            };

            HttpRequestHandler httpRequestHandler = new HttpRequestHandler();
            string             executeAsync       = await httpRequestHandler.ReadAsStringAsync(httpRequestItem);

            //TODO : Investigate
            //return JsonConvert.DeserializeObject<User>(executeAsync);
        }
Exemplo n.º 8
0
        protected BaseManager(Config config, AuthorizationHeader authorizationHeader)
        {
            AuthorizationHeader = authorizationHeader;
            Config = config;

            HttpRequestHandler = new HttpRequestHandler();
        }
        /// <summary>
        /// An authentication response have been received from the web browser.
        /// Check if it's correct
        /// </summary>
        /// <param name="header">Contents from the Authorization header</param>
        /// <param name="realm">Realm that should be authenticated</param>
        /// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param>
        /// <param name="options">First option: true if username/password is correct but not cnonce</param>
        /// <returns>
        /// Authentication object that is stored for the request. A user class or something like that.
        /// </returns>
        /// <exception cref="ArgumentException">if authenticationHeader is invalid</exception>
        /// <exception cref="ArgumentNullException">If any of the parameters is empty or null.</exception>
        public bool Authenticate(AuthorizationHeader header, string realm, string httpVerb, object[] options)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            lock (_nonces)
            {
                if (_timer == null)
                {
                    _timer = new Timer(ManageNonces, null, 15000, 15000);
                }
            }

            if (!header.Scheme.Equals("digest", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            var parameters = HeaderParameterCollection.Parse(new StringReader(header.Data));

            if (!IsValidNonce(parameters["nonce"]) && !DisableNonceCheck)
            {
                return(false);
            }

            // request authentication information
            string        username = parameters["username"];
            DigestContext context  = new DigestContext(realm, username);

            if (!_authenticator(context))
            {
                return(false);
            }


            // Encode authentication info
            string HA1;

            if (string.IsNullOrEmpty(context.HA1))
            {
                string A1 = String.Format("{0}:{1}:{2}", username, realm, context.Password);
                HA1 = GetMD5HashBinHex2(A1);
            }
            else
            {
                HA1 = context.HA1;
            }

            // encode challenge info
            string A2           = String.Format("{0}:{1}", httpVerb, parameters["uri"]);
            string HA2          = GetMD5HashBinHex2(A2);
            string hashedDigest = Encrypt(HA1, HA2, parameters["qop"],
                                          parameters["nonce"], parameters["nc"], parameters["cnonce"]);

            //validate
            return(parameters["response"] == hashedDigest);
        }
Exemplo n.º 10
0
        public CopyClient(Config config)
        {
            _authorizationHeader = new AuthorizationHeader();
            Config = config;


            InitManagers();
        }
Exemplo n.º 11
0
 public IHeader Parse(string name, ITextReader reader)
 {
   var header = new AuthorizationHeader();
   reader.ConsumeWhiteSpaces();
   header.Scheme = reader.ReadWord();
   reader.ConsumeWhiteSpaces();
   header.Data = reader.ReadToEnd();
   return header;
 }
Exemplo n.º 12
0
        public static void AddAuthorizationHeader(this WebRequest request, ExceptionlessConfiguration configuration)
        {
            var authorizationHeader = new AuthorizationHeader {
                Scheme        = ExceptionlessHeaders.Bearer,
                ParameterText = configuration.ApiKey
            };

            request.Headers[HttpRequestHeader.Authorization] = authorizationHeader.ToString();
        }
Exemplo n.º 13
0
 public IHeader Parse(string name, ITextReader reader)
 {
     var header = new AuthorizationHeader();
     reader.ConsumeWhiteSpaces();
     header.Scheme = reader.ReadWord();
     reader.ConsumeWhiteSpaces();
     header.Data = reader.ReadToEnd();
     return header;
 }
Exemplo n.º 14
0
        public void SignRequest(WebRequest request)
        {
            Nonce               nonce     = Nonce.Generate();
            TimeStamp           timestamp = TimeStamp.Generate();
            Signature           signature = GenerateSignature(request, nonce, timestamp);
            AuthorizationHeader header    = GenerateAuthorizationHeader(nonce, timestamp, signature);

            AddAuthorizationHeaderToRequest(request, header);
        }
Exemplo n.º 15
0
        /// <summary>
        /// An authentication response have been received from the web browser.
        /// Check if it's correct
        /// </summary>
        /// <param name="header">Contents from the Authorization header</param>
        /// <param name="realm">Realm that should be authenticated</param>
        /// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param>
        /// <returns>
        /// Authentication object that is stored for the request. A user class or something like that.
        /// </returns>
        /// <exception cref="ArgumentException">if authenticationHeader is invalid</exception>
        /// <exception cref="ArgumentNullException">If any of the parameters is empty or null.</exception>
        public IAuthenticationUser Authenticate(AuthorizationHeader header, string realm, string httpVerb)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            lock (_nonces)
            {
                if (_timer == null)
                {
                    _timer = new Timer(ManageNonces, null, 15000, 15000);
                }
            }

            if (!header.Scheme.Equals("digest", StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var parameters = HeaderParameterCollection.Parse(new StringReader(header.Data), ',');

            if (!IsValidNonce(parameters["nonce"]) && !DisableNonceCheck)
            {
                return(null);
            }

            // request authentication information
            string username = parameters["username"];
            var    user     = _userProvider.Lookup(username, realm);

            if (user == null)
            {
                return(null);
            }



            // Encode authentication info
            string HA1 = string.IsNullOrEmpty(user.HA1) ? GetHA1(realm, username, user.Password) : user.HA1;

            // encode challenge info
            string A2           = String.Format("{0}:{1}", httpVerb, parameters["uri"]);
            string HA2          = GetMD5HashBinHex2(A2);
            string hashedDigest = Encrypt(HA1, HA2, parameters["qop"],
                                          parameters["nonce"], parameters["nc"], parameters["cnonce"]);

            //validate
            if (parameters["response"] == hashedDigest)
            {
                return(user);
            }

            return(null);
        }
Exemplo n.º 16
0
        /// <summary>
        /// An authentication response have been received from the web browser.
        /// Check if it's correct
        /// </summary>
        /// <param name="header">Authorization header</param>
        /// <param name="realm">Realm that should be authenticated</param>
        /// <param name="httpVerb">GET/POST/PUT/DELETE etc.</param>
        /// <returns>Authentication object that is stored for the request. A user class or something like that.</returns>
        /// <exception cref="ArgumentException">if authenticationHeader is invalid</exception>
        /// <exception cref="ArgumentNullException">If any of the paramters is empty or null.</exception>
        public IAuthenticationUser Authenticate(AuthorizationHeader header, string realm, string httpVerb)
        {
            if (header == null)
            {
                throw new ArgumentNullException("realm");
            }
            if (string.IsNullOrEmpty(realm))
            {
                throw new ArgumentNullException("realm");
            }
            if (string.IsNullOrEmpty(httpVerb))
            {
                throw new ArgumentNullException("httpVerb");
            }

            /*
             * To receive authorization, the client sends the userid and password,
             *  separated by a single colon (":") character, within a base64 [7]
             *  encoded string in the credentials.*/
            string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(header.Data));
            int    pos     = decoded.IndexOf(':');

            if (pos == -1)
            {
                throw new BadRequestException("Invalid basic authentication header, failed to find colon.");
            }

            string password = decoded.Substring(pos + 1, decoded.Length - pos - 1);
            string userName = decoded.Substring(0, pos);

            var user = _userProvider.Lookup(userName, realm);

            if (user == null)
            {
                return(null);
            }

            if (user.Password == null)
            {
                var ha1 = DigestAuthentication.GetHA1(realm, userName, password);
                if (ha1 != user.HA1)
                {
                    return(null);
                }
            }
            else
            {
                if (password != user.Password)
                {
                    return(null);
                }
            }

            return(user);
        }
Exemplo n.º 17
0
        public void Shall_clone_header()
        {
            var original = AuthorizationHeader.Parse("Basic qop=\"auth\"");
            var cloned   = original.DeepClone();

            original.AuthenticationType = "Digest";
            original.MessageQop         = null;
            original.CNonce             = "\"abc\"";

            Assert.That(cloned.ToString(), Is.EqualTo("Basic qop=\"auth\""));
            Assert.That(original.ToString(), Is.EqualTo("Digest cnonce=\"abc\""));
        }
        /// <summary>
        ///     Populates the httpClient with signed request headers and the POST body data.
        /// </summary>
        /// <param name="message">
        ///     The http request message.
        /// </param>
        /// <param name="postBody">
        ///     The post body data of the request.
        /// </param>
        /// <param name="contentType">
        ///     Either JSON or XML.
        /// </param>
        /// <param name="developerKey">
        ///     The developer key used to create the signed header.
        /// </param>
        /// <param name="developerSecret">
        ///     The developer secret used to create the signed header.
        /// </param>
        private void CreateRequestHeaders(HttpRequestMessage message, string postBody, string contentType, string developerKey, string developerSecret)
        {
            AuthorizationHeader authorizationHeader = AuthorizationHeader.Create(message.Headers, message.RequestUri, postBody, message.Method.Method, "1.0", "TP-HMAC-SHA1", Guid.NewGuid().ToString(), DateTime.UtcNow.ToString("O"), developerKey, developerSecret);

            message.Headers.Add("tp-authorization", authorizationHeader.ToString());
            message.Headers.Add("tp-application-id", "1234");
            message.Headers.Add("tp-application-name", "triPOS.CSharp");
            message.Headers.Add("tp-application-version", "1.0.0");
            message.Headers.Add("tp-return-logs", "false");
            message.Headers.Add("accept", contentType);
            message.Content = new StringContent(postBody, Encoding.UTF8, contentType);
        }
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var authHeader = new AuthorizationHeader(_hashKeys.APPId);

            authHeader.Signature = await _signer.SignAsync(request, authHeader, _hashKeys);

            request.Headers.Authorization = new AuthenticationHeaderValue(_authHeaderSerializer.AuthenticationScheme, _authHeaderSerializer.Serialize(authHeader));

            var response = await base.SendAsync(request, cancellationToken);

            return(response);
        }
        public override bool ProcessRow(DataRow row)
        {
            string barcode = GetStringFieldValue(row, "Barcode");

            using (var ws = new OperationHistory12())
            {
                OperationHistoryRequest request = new OperationHistoryRequest();
                request.Barcode     = barcode;
                request.Language    = "RUS";
                request.MessageType = 0;

                AuthorizationHeader ah = new AuthorizationHeader();
                ah.login          = "******";
                ah.password       = "******";
                ah.mustUnderstand = true;

                var Values = ws.getOperationHistory(request, ah);


                OperationHistoryRecord latestOperation = null;
                bool IsReturned = false;
                foreach (var Value in Values)
                {
                    if (Value.OperationParameters.OperType.Name == "Возврат")
                    {
                        IsReturned = true;
                    }
                    if (latestOperation == null || latestOperation.OperationParameters.OperDate < Value.OperationParameters.OperDate)
                    {
                        latestOperation = Value;
                    }
                }

                if (latestOperation != null)
                {
                    string lastStatus = string.Empty;
                    if (IsReturned)
                    {
                        lastStatus = "Возврат!!!";
                    }

                    lastStatus += latestOperation.OperationParameters.OperType.Name + ":" + latestOperation.OperationParameters.OperAttr.Name;
                    DateTime latestDate = latestOperation.OperationParameters.OperDate;
                    SetStringFieldValue(row, "Status", lastStatus);
                    if (Fieldsmap.ContainsKey("Date"))
                    {
                        SetStringFieldValue(row, "Date", latestDate.ToString("yyyy.MM.dd H:mm:ss"));
                    }
                }
            }
            return(true);
        }
Exemplo n.º 21
0
        private HttpRequestItem CreateHttpRequestItem(string url, HttpMethod httpMethod, HttpContent httpContent = null)
        {
            string authzHeader = AuthorizationHeader.CreateForREST(Config.ConsumerKey, Config.ConsumerSecret, AuthToken.Token, AuthToken.TokenSecret, url, httpMethod.ToString());

            return(new HttpRequestItem()
            {
                URL = url,
                HttpMethod = httpMethod,
                AuthzHeader = authzHeader,
                HttpContent = httpContent,
                IsDataRequest = true
            });
        }
    public override bool CheckAccess(OperationContext operationContext, ref Message message)
    {
        var reqProp    = message.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
        var authHeader = new AuthorizationHeader(reqProp.Headers[HttpRequestHeader.Authorization]);

        var authorized =         // decide if this message is authorized...

                         if (!authorized)
        {
            var webContext = new WebOperationContext(operationContext);
            webContext.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
            webContext.OutgoingResponse.Headers.Add(HttpResponseHeader.WwwAuthenticate, String.Format("Bearer realm=\"{0}\"", baseUri.AbsoluteUri));
        }

        return(authorized);
    }
        public void Signing_with_null_message_body_should_succeed()
        {
            // arrange
            var signer     = new Signer();
            var hashKeys   = HashKeys.GenerateHashKeys("747D1358-89E4-4A49-BFB3-65E020D1D4BD", "MD5", "HMACSHA256", "MY_APPID");
            var authHeader = new AuthorizationHeader(hashKeys.APPId);
            var httpMethod = "GET";
            var requstUrl  = @"https:\\LOCALHOST\MyApi\WonderLand";

            // action
            var signature = signer.Sign(requstUrl, httpMethod, null, authHeader, hashKeys);

            // assert
            signature.ShouldNotBeNull();
            signature.ShouldNotBeEmpty();
            signature.Length.ShouldBe(44);
        }
        public void Signing_with_same_url_with_different_casing_should_not_generate_same_signatures()
        {
            // arrange
            var signer     = new Signer();
            var hashKeys   = HashKeys.GenerateHashKeys("747D1358-89E4-4A49-BFB3-65E020D1D4BD", "MD5", "HMACSHA256", "MY_APPID");
            var authHeader = new AuthorizationHeader(hashKeys.APPId);
            var httpMethod = "GET";
            var requstUrl1 = @"HTTPS:\\localhost\MYAPI\WONDERLAND";
            var requstUrl2 = @"https:\\LOCALHOST\MyApi\wonderland";

            // action
            var signature1 = signer.Sign(requstUrl1, httpMethod, null, authHeader, hashKeys);
            var signature2 = signer.Sign(requstUrl2, httpMethod, null, authHeader, hashKeys);

            // assert
            signature1.ShouldNotBe(signature2);
        }
        public void Signing_async_with_should_succeedAsync()
        {
            // arrange
            var signer     = new Signer();
            var hashKeys   = new HashKeys("ae5d53eb-e000-4de0-93a9-a70aa61300bf", "E0wMj/lLap3nmzOVYQUKdOlo/EuQRsFh76gxAaPRqZk=", "MD5", "HMACSHA256", "4735e15e-b85c-4010-b641-5736e9483b03");
            var authHeader = new AuthorizationHeader(hashKeys.APPId);
            var request    = new HttpRequestMessage {
                Content = null, Method = HttpMethod.Get, RequestUri = new Uri("https://localhost:44321/HealthData/shared", UriKind.Absolute)
            };

            // action
            var signature = signer.SignAsync(request, authHeader, hashKeys).Result;

            // assert
            signature.ShouldNotBeNull();
            signature.ShouldNotBeEmpty();
            signature.Length.ShouldBe(44);
        }
Exemplo n.º 26
0
        public async Task <Account> AuthenticateAsync(HttpContext httpContext)
        {
            // httpContext is a required parameter
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            // If there is not a Authorization header in the request, then we
            // cannot authenticate.
            if (!httpContext.Request.Headers
                .TryGetValue("Authorization", out var authorizationValues))
            {
                throw new AuthenticationException(
                          "The HTTP request did not contain a 'Authorization' header.",
                          AuthenticationErrorCode.MissingHeader
                          );
            }

            // Pick the most secure/fastest way to authenticate if there are multiple
            // options.
            AuthorizationHeader auth = PickBestAuthenticationMethod(
                authorizationValues.Select(s => new AuthorizationHeader(s))
                );

            if (auth == null)
            {
                throw new AuthenticationException(
                          "An 'Authorization' header was supplied but no usable authentication method was found.",
                          AuthenticationErrorCode.NoUsableMethodFound
                          );
            }
            switch (auth.Method)
            {
            case AuthenticationMethod.Basic:
                return(await HandleBasicAuthentication(httpContext, auth.Credentials));

            default:
                throw new AuthenticationException(
                          "Unhandled authentication method.",
                          AuthenticationErrorCode.UnhandledMethod
                          );
            }
        }
Exemplo n.º 27
0
        protected AuthorizationHeader CreateAuthHeader(HttpWebRequest request)
        {
            var parameters = new HttpParameterSet()
            {
                // From AuthConfig
                ConsumerKey     = config.ConsumerKey,
                ConsumerSecret  = config.ConsumerSecret,
                Token           = config.Token,
                TokenSecret     = config.TokenSecret,
                OAuthVersion    = config.OAuthVersion,
                SignatureMethod = config.SignatureMethod,

                // Derived from HTTP Web Request
                Url           = request.RequestUri.OriginalString,
                RequestMethod = request.Method,
                PostData      = postData,
            };

            return(AuthorizationHeader.Create(parameters));
        }
Exemplo n.º 28
0
        public async Task <User> GetUserAsync()
        {
            string url = string.Format("{0}/{1}", URL.RESTRoot, "user");

            string authzHeader = AuthorizationHeader.CreateForREST(Config.ConsumerKey, Config.ConsumerSecret, AuthToken.Token, AuthToken.TokenSecret, url, "GET");

            HttpRequestItem httpRequestItem = new HttpRequestItem()
            {
                URL           = url,
                HttpMethod    = HttpMethod.Get,
                AuthzHeader   = authzHeader,
                HttpContent   = null,
                IsDataRequest = true
            };

            HttpRequestHandler httpRequestHandler = new HttpRequestHandler();
            string             executeAsync       = await httpRequestHandler.ReadAsStringAsync(httpRequestItem);

            return(JsonConvert.DeserializeObject <User>(executeAsync));
        }
Exemplo n.º 29
0
        public void PassTestSuite(params string[] scenarioName)
        {
            // Arrange
            var scenario = context.LoadScenario(scenarioName);

            // Add header 'X-Amz-Date' since the algorithm at this point expects it on the request
            scenario.Request.AddHeader(HeaderKeys.XAmzDateHeader, context.UtcNow.ToIso8601BasicDateTime());

            // Act
            var authorizationHeader = AuthorizationHeader.Build(
                context.UtcNow,
                context.RegionName,
                context.ServiceName,
                context.Credentials,
                scenario.ExpectedSignedHeaders,
                scenario.ExpectedCredentialScope,
                scenario.ExpectedStringToSign);

            // Assert
            authorizationHeader.ShouldBe(scenario.ExpectedAuthorizationHeader);
        }
Exemplo n.º 30
0
        public Fixture Then_we_can_connect()
        {
            var oAuthParameters = new OAuthParameters(
                _consumer.ConsumerKey,
                new TokenKey(_consumer.ConsumerKey.Value),
                "RSA-SHA1",
                new DefaultTimestampSequence(),
                new DefaultNonceSequence(),
                string.Empty,
                "1.0"
                );

            var earl = new Uri("https://api.xero.com/api.xro/2.0/Organisation");

            var signatureBaseString =
                new SignatureBaseString(
                    new Request
            {
                Url  = earl,
                Verb = "GET"
            },
                    oAuthParameters
                    );

            var signature = new RsaSha1(_cert).Sign(signatureBaseString);

            oAuthParameters.SetSignature(signature);

            var header = new AuthorizationHeader(oAuthParameters, string.Empty);

            var req = (HttpWebRequest)WebRequest.Create(earl);

            req.Headers.Add("Authorization", header.Value);

            var response = TInternet.Get(req);
            const HttpStatusCode expected = HttpStatusCode.OK;
            var actual = response.StatusCode;

            return(new YesNoFixture(actual == expected, "Expected [" + expected + "]. Got [" + actual + "]. And here is the body: " + response.Body, 2));
        }
Exemplo n.º 31
0
        private bool AuthorizeRequest(HttpRequestMessage request)
        {
            bool authorized = false;

            bool validDeviceID           = false;
            bool validRequestToken       = false;
            bool ValidCredentials        = false;
            bool validAuthorizationToken = false;

            // Find Header
            if (request.Headers.Contains(OAuthConstants.AuthorzationHeader))
            {
                var tokenValue = request.Headers.GetValues(OAuthConstants.AuthorzationHeader);
                if (tokenValue.Count() == 1)
                {
                    var value  = tokenValue.FirstOrDefault();
                    var header = new AuthorizationHeader(value);

                    switch (header.Scheme)
                    {
                    case "Request":
                        //validDeviceID = ValidateDeviceID(header.ParameterText.Trim());
                        break;
                    }

                    if (string.Equals(header.Scheme, "OAuth", StringComparison.OrdinalIgnoreCase))
                    {
                        if (string.Equals(header.Scheme, "OAuth", StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);// header.ParameterText.Trim();
                        }
                    }
                    //Token validation logic here
                    //set authorized variable accordingly
                }
            }
            return(authorized);
        }