// Invoked after the user has authorized us
        // TODO: this should return the stream error for invalid passwords instead of just true/false.
        public bool AcquireAccessToken(string requestTokenSecret, string authorizationToken, string authorizationVerifier)
        {
            var headers = new Dictionary <string, string> {
                { "oauth_consumer_key", provider.ConsumerKey },
                { "oauth_nonce", MakeNonce() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", MakeTimestamp() },
                { "oauth_version", "1.0" }
            };
            var content = "";

            if (xAuthUsername == null)
            {
                headers.Add("oauth_token", OAuthUtils.PercentEncode(authorizationToken));
                headers.Add("oauth_verifier", OAuthUtils.PercentEncode(authorizationVerifier));
            }
            else
            {
                headers.Add("x_auth_username", OAuthUtils.PercentEncode(xAuthUsername));
                headers.Add("x_auth_password", OAuthUtils.PercentEncode(xAuthPassword));
                headers.Add("x_auth_mode", "client_auth");
                content = $"x_auth_mode=client_auth&x_auth_password={OAuthUtils.PercentEncode(xAuthPassword)}&x_auth_username={OAuthUtils.PercentEncode(xAuthUsername)}";
            }

            string signature           = MakeSignature("POST", provider.AccessTokenUrl, headers);
            string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, requestTokenSecret);
            string oauth_signature     = MakeOAuthSignature(compositeSigningKey, signature);

            headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
            if (xAuthUsername != null)
            {
                headers.Remove("x_auth_username");
                headers.Remove("x_auth_password");
                headers.Remove("x_auth_mode");
            }

            try
            {
                var strResponse = provider.AccessTokenUrl.PostStringToUrl(content,
                                                                          contentType: MimeTypes.FormUrlEncoded,
                                                                          requestFilter: req => req.AddHeader(HttpHeaders.Authorization, HeadersToOAuth(headers)));

                var result = PclExportClient.Instance.ParseQueryString(strResponse);
                if (result["oauth_token"] != null)
                {
                    AccessToken       = result["oauth_token"];
                    AccessTokenSecret = result["oauth_token_secret"];
                    AuthInfo          = result.ToDictionary();

                    return(true);
                }
            }
            catch (WebException ex)
            {
                var x = ex.Response.ResponseStream();
                log.Error(x.ReadToEnd(), ex);
                // fallthrough for errors
            }
            return(false);
        }
Exemple #2
0
        // Makes an OAuth signature out of the HTTP method, the base URI and the headers
        static string MakeSignature(string method, string base_uri, Dictionary <string, string> headers)
        {
            var items = from k in headers.Keys
                        orderby k
                        select k + "%3D" + OAuthUtils.PercentEncode(headers[k]);

            return(method + "&" + OAuthUtils.PercentEncode(base_uri) + "&" +
                   string.Join("%26", items.ToArray()));
        }
        public bool AcquireRequestToken()
        {
            var headers = new Dictionary <string, string>
            {
                { "oauth_callback", OAuthUtils.PercentEncode(provider.CallbackUrl) },
                { "oauth_consumer_key", provider.ConsumerKey },
                { "oauth_nonce", MakeNonce() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", MakeTimestamp() },
                { "oauth_version", "1.0" }
            };

            var uri = new Uri(provider.RequestTokenUrl);

            var signatureHeaders = new Dictionary <string, string>(headers);

            var nvc = PclExportClient.Instance.ParseQueryString(uri.Query);

            foreach (string key in nvc)
            {
                if (key != null)
                {
                    signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key]));
                }
            }

            string signature           = MakeSignature("POST", uri.AbsoluteUri.LeftPart('?'), signatureHeaders);
            string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, null);
            string oauth_signature     = MakeOAuthSignature(compositeSigningKey, signature);

            headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));

            try
            {
                var strResponse = provider.RequestTokenUrl.PostStringToUrl("", requestFilter: req => {
                    req.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);
                });
                var result = PclExportClient.Instance.ParseQueryString(strResponse);

                if (result["oauth_callback_confirmed"] != null)
                {
                    RequestToken       = result["oauth_token"];
                    RequestTokenSecret = result["oauth_token_secret"];

                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                string responseBody = e.GetResponseBody();
                responseBody.Print();
                // fallthrough for errors
            }
            return(false);
        }
Exemple #4
0
        // Makes an OAuth signature out of the HTTP method, the base URI and the headers
        static string MakeSignature(string method, string base_uri, Dictionary <string, string> headers)
        {
            var emptyHeaders = headers.Keys.Where(k => string.IsNullOrEmpty(headers[k])).ToArray();

            if (emptyHeaders.Length > 0)
            {
                log.Warn("Empty Headers: " + string.Join(", ", emptyHeaders));
            }

            var items = headers.Keys.OrderBy(k => k)
                        .Select(k => k + "%3D" + OAuthUtils.PercentEncode(headers[k]));

            return(method + "&" + OAuthUtils.PercentEncode(base_uri) + "&" +
                   string.Join("%26", items.ToArray()));
        }
        // Makes an OAuth signature out of the HTTP method, the base URI and the headers
        static string MakeSignature(string method, string base_uri, Dictionary <string, string> headers)
        {
            var emptyHeaders = headers.Keys.Where(k => string.IsNullOrEmpty(headers[k])).ToArray();

            if (emptyHeaders.Length > 0)
            {
                Logger.Warn("Empty Headers: " + string.Join(", ", emptyHeaders));
            }

            var sortedHeaders = !OrderHeadersLexically
                ? headers.Keys.OrderBy(k => k)
                : headers.Keys.OrderBy(k => k, StringComparer.Ordinal);

            var items = sortedHeaders.Select(k => k + "%3D" + OAuthUtils.PercentEncode(headers[k]));

            return(method
                   + "&" + OAuthUtils.PercentEncode(base_uri)
                   + "&" + string.Join("%26", items.ToArray()));
        }
Exemple #6
0
        /// <summary>
        /// The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally.
        /// Overridable so you can provide your own Auth implementation.
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="session"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                OAuthUtils.RequestToken          = tokens.RequestToken;
                OAuthUtils.RequestTokenSecret    = tokens.RequestTokenSecret;
                OAuthUtils.AuthorizationToken    = request.oauth_token;
                OAuthUtils.AuthorizationVerifier = request.oauth_verifier;

                if (OAuthUtils.AcquireAccessToken())
                {
                    session.IsAuthenticated  = true;
                    tokens.AccessToken       = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;

                    return(OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access
                }

                //No Joy :(
                tokens.RequestToken       = null;
                tokens.RequestTokenSecret = null;
                authService.SaveSession(session, SessionExpiry);
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken       = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                authService.SaveSession(session, SessionExpiry);

                //Redirect to OAuth provider to approve access
                return(authService.Redirect(AccessTokenUrlFilter(this, this.AuthorizeUrl
                                                                 .AddQueryParam("oauth_token", tokens.RequestToken)
                                                                 .AddQueryParam("oauth_callback", session.ReferrerUrl))));
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
Exemple #7
0
        //
        // Assign the result to the Authorization header, like this:
        // request.Headers [HttpRequestHeader.Authorization] = AuthorizeRequest (...)
        //
        public static string AuthorizeRequest(OAuthProvider provider, string oauthToken, string oauthTokenSecret, string method, Uri uri, string data)
        {
            var headers = new Dictionary <string, string>()
            {
                { "oauth_consumer_key", provider.ConsumerKey },
                { "oauth_nonce", MakeNonce() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", MakeTimestamp() },
                { "oauth_token", oauthToken },
                { "oauth_version", "1.0" }
            };
            var signatureHeaders = new Dictionary <string, string>(headers);

            // Add the data and URL query string to the copy of the headers for computing the signature
            if (!string.IsNullOrEmpty(data))
            {
                var parsed = HttpUtility.ParseQueryString(data);
                foreach (string k in parsed.Keys)
                {
                    signatureHeaders.Add(k, OAuthUtils.PercentEncode(parsed[k]));
                }
            }

            var nvc = HttpUtility.ParseQueryString(uri.Query);

            foreach (string key in nvc)
            {
                if (key != null)
                {
                    signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key]));
                }
            }

            string signature           = MakeSignature(method, uri.GetLeftPart(UriPartial.Path), signatureHeaders);
            string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret);
            string oauth_signature     = MakeOAuthSignature(compositeSigningKey, signature);

            headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));

            return(HeadersToOAuth(headers));
        }
        //
        // Used to authorize an HTTP request going to TwitPic
        //
        public static void AuthorizeTwitPic(OAuthProvider provider, HttpWebRequest wc, string oauthToken, string oauthTokenSecret)
        {
            var headers = new Dictionary <string, string>()
            {
                { "oauth_consumer_key", provider.ConsumerKey },
                { "oauth_nonce", MakeNonce() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", MakeTimestamp() },
                { "oauth_token", oauthToken },
                { "oauth_version", "1.0" },
                //{ "realm", "http://api.twitter.com" }
            };
            string signurl = "http://api.twitter.com/1/account/verify_credentials.xml";
            // The signature is not done against the *actual* url, it is done against the verify_credentials.json one
            string signature           = MakeSignature("GET", signurl, headers);
            string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret);
            string oauth_signature     = MakeOAuthSignature(compositeSigningKey, signature);

            headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));

            //Util.Log ("Headers: " + HeadersToOAuth (headers));
            wc.Headers["X-Verify-Credentials-Authorization"] = HeadersToOAuth(headers);
            wc.Headers["X-Auth-Service-Provider"]            = signurl;
        }
Exemple #9
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Transferring AccessToken/Secret from Mobile/Desktop App to Server
            if (request.AccessToken != null && request.AccessTokenSecret != null)
            {
                tokens.AccessToken       = request.AccessToken;
                tokens.AccessTokenSecret = request.AccessTokenSecret;

                var validToken = AuthHttpGateway.VerifyTwitterAccessToken(
                    ConsumerKey, ConsumerSecret,
                    tokens.AccessToken, tokens.AccessTokenSecret,
                    out var userId,
                    out var email);

                if (!validToken)
                {
                    return(HttpError.Unauthorized("AccessToken is invalid"));
                }

                if (!string.IsNullOrEmpty(request.UserName) && userId != request.UserName)
                {
                    return(HttpError.Unauthorized("AccessToken does not match UserId: " + request.UserName));
                }

                tokens.UserId           = userId;
                session.IsAuthenticated = true;

                var failedResult = OnAuthenticated(authService, session, tokens, new Dictionary <string, string>());
                var isHtml       = authService.Request.IsHtml();
                if (failedResult != null)
                {
                    return(ConvertToClientError(failedResult, isHtml));
                }

                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestTokenSecret.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                if (OAuthUtils.AcquireAccessToken(tokens.RequestTokenSecret, request.oauth_token, request.oauth_verifier))
                {
                    session.IsAuthenticated  = true;
                    tokens.AccessToken       = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;

                    return(OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access
                }

                //No Joy :(
                tokens.RequestToken       = null;
                tokens.RequestTokenSecret = null;
                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken       = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                this.SaveSession(authService, session, SessionExpiry);

                //Redirect to OAuth provider to approve access
                return(authService.Redirect(AccessTokenUrlFilter(this, this.AuthorizeUrl
                                                                 .AddQueryParam("oauth_token", tokens.RequestToken)
                                                                 .AddQueryParam("oauth_callback", session.ReferrerUrl)
                                                                 .AddQueryParam(Keywords.State, session.Id) // doesn't support state param atm, but it's here when it does
                                                                 )));
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }
 static string MakeSigningKey(string consumerSecret, string oauthTokenSecret)
 {
     return(OAuthUtils.PercentEncode(consumerSecret) + "&" + (oauthTokenSecret != null ? OAuthUtils.PercentEncode(oauthTokenSecret) : ""));
 }
Exemple #11
0
        // Invoked after the user has authorized us
        //
        // TODO: this should return the stream error for invalid passwords instead of
        // just true/false.
        public bool AcquireAccessToken()
        {
            var headers = new Dictionary <string, string>()
            {
                { "oauth_consumer_key", provider.ConsumerKey },
                { "oauth_nonce", MakeNonce() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", MakeTimestamp() },
                { "oauth_version", "1.0" }
            };
            var content = "";

            if (xAuthUsername == null)
            {
                headers.Add("oauth_token", OAuthUtils.PercentEncode(AuthorizationToken));
                headers.Add("oauth_verifier", OAuthUtils.PercentEncode(AuthorizationVerifier));
            }
            else
            {
                headers.Add("x_auth_username", OAuthUtils.PercentEncode(xAuthUsername));
                headers.Add("x_auth_password", OAuthUtils.PercentEncode(xAuthPassword));
                headers.Add("x_auth_mode", "client_auth");
                content = $"x_auth_mode=client_auth&x_auth_password={OAuthUtils.PercentEncode(xAuthPassword)}&x_auth_username={OAuthUtils.PercentEncode(xAuthUsername)}";
            }

            string signature           = MakeSignature("POST", provider.AccessTokenUrl, headers);
            string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, RequestTokenSecret);
            string oauth_signature     = MakeOAuthSignature(compositeSigningKey, signature);

            var wc = new WebClient();

            headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature));
            if (xAuthUsername != null)
            {
                headers.Remove("x_auth_username");
                headers.Remove("x_auth_password");
                headers.Remove("x_auth_mode");
            }
            wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers);

            try
            {
                var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.AccessTokenUrl), content));

                if (result["oauth_token"] != null)
                {
                    AccessToken       = result["oauth_token"];
                    AccessTokenSecret = result["oauth_token_secret"];
                    AuthInfo          = result.ToDictionary();

                    return(true);
                }
            }
            catch (WebException e)
            {
                var x = e.Response.GetResponseStream();
                var j = new System.IO.StreamReader(x);
                Console.WriteLine(j.ReadToEnd());
                Console.WriteLine(e);
                // fallthrough for errors
            }
            return(false);
        }
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var tokens = Init(authService, ref session, request);

            //Transfering AccessToken/Secret from Mobile/Desktop App to Server
            if (request.AccessToken != null && request.AccessTokenSecret != null)
            {
                session.IsAuthenticated = true;

                long userId;
                if (request.UserName != null && long.TryParse(request.UserName, out userId))
                {
                    tokens.UserId = userId.ToString();
                }

                tokens.AccessToken       = request.AccessToken;
                tokens.AccessTokenSecret = request.AccessTokenSecret;

                var authResponse = OnAuthenticated(authService, session, tokens, new Dictionary <string, string>());
                if (authResponse != null)
                {
                    return(authResponse);
                }

                var isHtml = authService.Request.ResponseContentType.MatchesContentType(MimeTypes.Html);
                return(isHtml
                    ? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))
                    : null); //return default AuthenticateResponse
            }

            //Default OAuth logic based on Twitter's OAuth workflow
            if (!tokens.RequestToken.IsNullOrEmpty() && !request.oauth_token.IsNullOrEmpty())
            {
                OAuthUtils.RequestToken          = tokens.RequestToken;
                OAuthUtils.RequestTokenSecret    = tokens.RequestTokenSecret;
                OAuthUtils.AuthorizationToken    = request.oauth_token;
                OAuthUtils.AuthorizationVerifier = request.oauth_verifier;

                if (OAuthUtils.AcquireAccessToken())
                {
                    session.IsAuthenticated  = true;
                    tokens.AccessToken       = OAuthUtils.AccessToken;
                    tokens.AccessTokenSecret = OAuthUtils.AccessTokenSecret;

                    return(OnAuthenticated(authService, session, tokens, OAuthUtils.AuthInfo)
                           ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access
                }

                //No Joy :(
                tokens.RequestToken       = null;
                tokens.RequestTokenSecret = null;
                this.SaveSession(authService, session, SessionExpiry);
                return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "AccessTokenFailed"))));
            }
            if (OAuthUtils.AcquireRequestToken())
            {
                tokens.RequestToken       = OAuthUtils.RequestToken;
                tokens.RequestTokenSecret = OAuthUtils.RequestTokenSecret;
                this.SaveSession(authService, session, SessionExpiry);

                //Redirect to OAuth provider to approve access
                return(authService.Redirect(AccessTokenUrlFilter(this, this.AuthorizeUrl
                                                                 .AddQueryParam("oauth_token", tokens.RequestToken)
                                                                 .AddQueryParam("oauth_callback", session.ReferrerUrl))));
            }

            return(authService.Redirect(FailedRedirectUrlFilter(this, session.ReferrerUrl.SetParam("f", "RequestTokenFailed"))));
        }