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"]));
                    }
        }
Пример #2
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\""));
        }
Пример #3
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();
        }
        /// <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);
        }
Пример #5
0
 private void AddAuthorizationHeaderToRequest(WebRequest request, AuthorizationHeader header)
 {
     request.Headers.Add(HttpRequestHeader.Authorization, header.ToString());
 }
Пример #6
0
 internal void ClearAuthReq(HttpWebRequest httpWebRequest)
 {
     //
     // if we are authenticating and we're being redirected to
     // another authentication space then remove the current
     // authentication header
     //
     GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::ClearAuthReq() httpWebRequest#" + ValidationHelper.HashString(httpWebRequest) + " " + AuthorizationHeader.ToString() + ": " + ValidationHelper.ToString(httpWebRequest.Headers[AuthorizationHeader]));
     TriedPreAuth  = false;
     Authorization = null;
     UniqueGroupId = null;
     httpWebRequest.Headers.Remove(AuthorizationHeader);
 }
Пример #7
0
        //
        // attempts to authenticate the request:
        // returns true only if it succesfully called into the AuthenticationManager
        // and got back a valid Authorization and succesfully set the appropriate auth headers
        //
        internal bool AttemptAuthenticate(HttpWebRequest httpWebRequest, ICredentials authInfo)
        {
            //
            // Check for previous authentication attempts or the presence of credentials
            //
            GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() httpWebRequest#" + ValidationHelper.HashString(httpWebRequest) + " AuthorizationHeader:" + AuthorizationHeader.ToString());

            if (Authorization != null && Authorization.Complete)
            {
                //
                // here the design gets "dirty".
                // if this is proxy auth, we might have been challenged by an external
                // server as well. in this case we will have to clear our previous proxy
                // auth state before we go any further. this will be broken if the handshake
                // requires more than one dropped connection (which NTLM is a border case for,
                // since it droppes the connection on the 1st challenge but not on the second)
                //
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() Authorization!=null Authorization.Complete:" + Authorization.Complete.ToString());
                if (IsProxyAuth)
                {
                    //
                    // so, we got passed a 407 but now we got a 401, the proxy probably
                    // dropped the connection on us so we need to reset our proxy handshake
                    // Consider: this should have been taken care by Update()
                    //
                    GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() ProxyAuth cleaning up auth status");
                    ClearAuthReq(httpWebRequest);
                }
                return(false);
            }

            if (authInfo == null)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() authInfo==null Authorization#" + ValidationHelper.HashString(Authorization));
                return(false);
            }

            string challenge = httpWebRequest.AuthHeader(AuthenticateHeader);

            if (challenge == null)
            {
                //
                // the server sent no challenge, but this might be the case
                // in which we're succeeding an authorization handshake to
                // a proxy while a handshake with the server is still in progress.
                // if the handshake with the proxy is complete and we actually have
                // a handshake with the server in progress we can send the authorization header for the server as well.
                //
                if (!IsProxyAuth && Authorization != null && httpWebRequest.ProxyAuthenticationState.Authorization != null)
                {
                    httpWebRequest.Headers.Set(AuthorizationHeader, Authorization.Message);
                }
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() challenge==null Authorization#" + ValidationHelper.HashString(Authorization));
                return(false);
            }

            //
            // if the AuthenticationManager throws on Authenticate,
            // bubble up that Exception to the user
            //
            GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() challenge:" + challenge);

            PrepareState(httpWebRequest);
            try {
                Authorization = AuthenticationManager.Authenticate(challenge, httpWebRequest, authInfo);
            }
            catch (Exception exception) {
                Authorization = null;
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() PreAuthenticate() returned exception:" + exception.Message);
                ClearSession(httpWebRequest);
                throw;
            }


            if (Authorization == null)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() Authorization==null");
                return(false);
            }
            if (Authorization.Message == null)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() Authorization.Message==null");
                Authorization = null;
                return(false);
            }

            UniqueGroupId = Authorization.ConnectionGroupId;
            GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() AuthorizationHeader:" + AuthorizationHeader + " blob: " + Authorization.Message.Length + "bytes Complete:" + Authorization.Complete.ToString());

            try {
                //
                // a "bad" module could try sending bad characters in the HTTP headers.
                // catch the exception from WebHeaderCollection.CheckBadChars()
                // fail the auth process
                // and return the exception to the user as InnerException
                //
                httpWebRequest.Headers.Set(AuthorizationHeader, Authorization.Message);
            }
            catch {
                Authorization = null;
                ClearSession(httpWebRequest);
                throw;
            }

            return(true);
        }
        //
        // attempts to authenticate the request:
        // returns true only if it succesfully called into the AuthenticationManager
        // and got back a valid Authorization and succesfully set the appropriate auth headers
        //
        internal bool AttemptAuthenticate(HttpWebRequest httpWebRequest, ICredentials authInfo)
        {
            //
            // Check for previous authentication attempts or the presence of credentials
            //
            GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() httpWebRequest#" + ValidationHelper.HashString(httpWebRequest) + " AuthorizationHeader:" + AuthorizationHeader.ToString());

            if (Authorization != null && Authorization.Complete)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() Authorization!=null Authorization.Complete:" + Authorization.Complete.ToString());
                if (IsProxyAuth)
                {
                    GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() ProxyAuth cleaning up auth status");
                    ClearAuthReq(httpWebRequest);
                }
                return(false);
            }

            if (authInfo == null)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() authInfo==null Authorization#" + ValidationHelper.HashString(Authorization));
                return(false);
            }

            string challenge = httpWebRequest.AuthHeader(AuthenticateHeader);

            if (challenge == null)
            {
                //
                // the server sent no challenge, but this might be the case
                // in which we're succeeding an authorization handshake to
                // a proxy while a handshake with the server is still in progress.
                // if the handshake with the proxy is complete and we actually have
                // a handshake with the server in progress we can send the authorization header for the server as well.
                //
                if (!IsProxyAuth && Authorization != null && httpWebRequest.ProxyAuthenticationState.Authorization != null)
                {
                    httpWebRequest.Headers.Set(AuthorizationHeader, Authorization.Message);
                }
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() challenge==null Authorization#" + ValidationHelper.HashString(Authorization));
                return(false);
            }

            //
            // if the AuthenticationManager throws on Authenticate,
            // bubble up that Exception to the user
            //
            GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() challenge:" + challenge);

            PrepareState(httpWebRequest);
            try {
                Authorization = AuthenticationManager.Authenticate(challenge, httpWebRequest, authInfo);
            }
            catch (Exception exception) {
                Authorization = null;
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() PreAuthenticate() returned exception:" + exception.Message);
                ClearSession(httpWebRequest);
                throw;
            }
            catch {
                Authorization = null;
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::PreAuthIfNeeded() PreAuthenticate() returned exception: Non-CLS Compliant Exception");
                ClearSession(httpWebRequest);
                throw;
            }


            if (Authorization == null)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() Authorization==null");
                return(false);
            }
            if (Authorization.Message == null)
            {
                GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() Authorization.Message==null");
                Authorization = null;
                return(false);
            }

            UniqueGroupId = Authorization.ConnectionGroupId;
            GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::AttemptAuthenticate() AuthorizationHeader:" + AuthorizationHeader + " blob: " + Authorization.Message.Length + "bytes Complete:" + Authorization.Complete.ToString());

            try {
                //
                // a "bad" module could try sending bad characters in the HTTP headers.
                // catch the exception from WebHeaderCollection.CheckBadChars()
                // fail the auth process
                // and return the exception to the user as InnerException
                //
                httpWebRequest.Headers.Set(AuthorizationHeader, Authorization.Message);
            }
            catch {
                Authorization = null;
                ClearSession(httpWebRequest);
                throw;
            }

            return(true);
        }