Ejemplo n.º 1
0
        public ActionResult OAuthCallback(string oauth_token, string oauth_verifier)
        {
            RequestTokenModel model        = new RequestTokenModel();
            RequestTokenModel sessionModel = Session["endpoints"] as RequestTokenModel;

            model = sessionModel;

            OAuthKeyConfiguration oauthConfiguration = OAuthKeyConfiguration.GetInstance();

            if (string.IsNullOrEmpty(oauth_verifier))
            {
                throw new Exception("Expected a non-empty verifier value");
            }

            OAuthClient oauthClient = new OAuthClient(sessionModel.EndpointModel, TestSite.MvcApplication.GetTokenManager(sessionModel.ConsumerKey, sessionModel.ConsumerSecret));

            if (oauthClient != null)
            {
                IOAuthToken oauthToken = oauthClient.ExchangeRequestTokenForAccessToken(oauth_verifier);

                if (oauthToken != null)
                {
                    model.Token  = oauthToken.Token;
                    model.Secret = oauthToken.Secret;
                }
            }

            return(View(model));
        }
Ejemplo n.º 2
0
        public void GetRequestToken(string consumerKey, string consumerSecret, string callbackUrl, string serviceUri, string requestTokenUri, string authorizationUri, string accessTokenUri)
        {
            RequestTokenModel model = new RequestTokenModel();

            model.ConsumerKey    = consumerKey;
            model.ConsumerSecret = consumerSecret;

            EndpointModel endpointModel = new EndpointModel();

            endpointModel.ServiceUri       = serviceUri;
            endpointModel.RequestTokenUri  = requestTokenUri;
            endpointModel.AuthorizationUri = authorizationUri;
            endpointModel.AccessTokenUri   = accessTokenUri;
            model.EndpointModel            = endpointModel;

            OAuthClientBase oauthClient = OAuthClient.CreateClient(consumerKey, consumerSecret, endpointModel);

            if (oauthClient != null)
            {
                IOAuthToken requestToken = oauthClient.GetRequestToken(this.GenerateRealm(TestUserId, "*****@*****.**"), callbackUrl);
                model.Token  = requestToken.Token;
                model.Secret = requestToken.Secret;
            }

            Session[model.Token] = model;

            string authorizationUrl = oauthClient.GetUserAuthorizationUrl(model);

            this.Response.Redirect(authorizationUrl, false);
        }
Ejemplo n.º 3
0
        public ActionResult GetInlineOAuthToken(string consumerKey, string consumerSecret, string callbackUrl, string serviceUri, string requestTokenUri, string authorizationUri, string accessTokenUri)
        {
            RequestTokenModel model = new RequestTokenModel();

            model.ConsumerKey    = consumerKey;
            model.ConsumerSecret = consumerSecret;

            EndpointModel endpointModel = new EndpointModel();

            endpointModel.ServiceUri       = serviceUri;
            endpointModel.RequestTokenUri  = requestTokenUri;
            endpointModel.AuthorizationUri = authorizationUri;
            endpointModel.AccessTokenUri   = accessTokenUri;
            model.EndpointModel            = endpointModel;

            OAuthClient oauthClient = new OAuthClient(model.ConsumerKey, model.ConsumerSecret, model.EndpointModel);

            try
            {
                IOAuthToken accessToken = oauthClient.GetInlineAccessToken(Realm.GetDefault());
                model.Token  = accessToken.Token;
                model.Secret = accessToken.Secret;
            }
            catch (OAuthException authEx)
            {
                Session["problem"] = authEx.Report;
                Response.Redirect("AccessDenied.aspx");
            }

            return(View("OauthCallback", model));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Authorize a request token
        /// </summary>
        /// <param name="oauthToken">The request token</param>
        /// <returns>An object containing a response elements (verifier code and granted)</returns>
        private TokenVerification InlineAuthorize(IOAuthToken oauthToken)
        {
            TokenVerification retVal = null;

            if (oauthToken != null)
            {
                RestClient  restClient = new RestClient(this.OAuthEndpoints.ServiceUri);
                RestRequest request    = new RestRequest(this.OAuthEndpoints.AuthorizationUri, Method.GET);
                request.AddParameter(Constants.TokenParameter, oauthToken.Token);
                var response = restClient.Execute(request);

                var    qs                     = HttpUtility.ParseQueryString(response.Content);
                string verifierCode           = qs[Constants.VerifierCodeParameter];
                string grantedAccessParameter = qs[Constants.GrantedAccessParameter];

                bool grantedAccess = false;
                if (!string.IsNullOrWhiteSpace(grantedAccessParameter))
                {
                    grantedAccess = bool.Parse(grantedAccessParameter);
                }

                if (!string.IsNullOrEmpty(verifierCode))
                {
                    retVal = new TokenVerification();
                    retVal.VerifierCode = verifierCode;
                    retVal.Granted      = grantedAccess;
                }
            }

            return(retVal);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Merges the properties from the <see cref="entity" /> into this entity
        /// </summary>
        /// <param name="entity">The entity to merge</param>
        public override void Merge(KeyedEntity entity)
        {
            Guard.NotNull(() => entity, entity);

            var mergeEntity = entity as OAuthTokenEntity;

            if (mergeEntity == null)
            {
                return;
            }

            IOAuthToken thisDto  = ToDto();
            IOAuthToken mergeDto = mergeEntity.ToDto();

            // Compare to see if we need to update changed values (null) values are ignored in persistence
            thisDto.Username    = mergeDto.Username.HasValue() ? mergeDto.Username : thisDto.Username;
            thisDto.AccessToken = mergeDto.AccessToken.HasValue()
                ? mergeDto.AccessToken
                : thisDto.AccessToken;
            thisDto.RefreshToken = mergeDto.RefreshToken.HasValue()
                ? mergeDto.RefreshToken
                : thisDto.RefreshToken;
            thisDto.ExpiresOnUtc = mergeDto.ExpiresOnUtc.HasValue() ? mergeDto.ExpiresOnUtc : thisDto.ExpiresOnUtc;
            thisDto.IssuedOnUtc  = mergeDto.IssuedOnUtc.HasValue() ? mergeDto.IssuedOnUtc : thisDto.IssuedOnUtc;

            //Convert back to entity
            OAuthTokenEntity thisEntity = FromDto(thisDto);

            Username     = thisEntity.Username;
            AccessToken  = thisEntity.AccessToken;
            RefreshToken = thisEntity.RefreshToken;
            ExpiresOnUtc = thisEntity.ExpiresOnUtc;
            IssuedOnUtc  = thisEntity.IssuedOnUtc;
        }
Ejemplo n.º 6
0
        public new void SetUp()
        {
            testServer = new RainyTestServer ();
            testServer.Start ();

            accessToken = testServer.GetAccessToken ();
            this.syncServer = new WebSyncServer (testServer.ListenUrl, accessToken);
        }
Ejemplo n.º 7
0
        public new void SetUp()
        {
            testServer = new RainyTestServer();
            testServer.Start();

            accessToken     = testServer.GetAccessToken();
            this.syncServer = new WebSyncServer(testServer.ListenUrl, accessToken);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Tomboy.Sync.Web.WebSyncServer"/> class.
        /// </summary>
        /// <param name="serverUrl">Server URL (without the api/1.0 part).</param>
        /// <param name="accessToken">An pre-obtained access token for OAuth.
        /// Use <see cref="PerformTokenExchange"/> or <see cref="PerformNonInteractiveTokenExchange"/>.
        /// </param>
        public WebSyncServer(string serverUrl, IOAuthToken accessToken)
        {
            rootApiUrl = serverUrl + "/api/1.0";
            this.accessToken = accessToken;

            this.DeletedServerNotes = new List<string> ();
            this.UploadedNotes = new List<Note> ();
        }
Ejemplo n.º 9
0
        public RequestToken GetRequestToken(string callback)
        {
            var requestPath = string.Format("{0}?{1}={2}", this.RequestTokenPath, OAuthParameter.OAUTH_CALLBACK,
                                            callback);
            IOAuthToken ioAuthToken = this.TokenRequest(this.HttpMethod, requestPath);

            return(new RequestToken(this, ioAuthToken, ((OAuthToken)ioAuthToken).CallbackConfirmed));
        }
Ejemplo n.º 10
0
 public WebTokenCreator(
     IUnityFactory <ITemporaryCredentials> applicationCredentialsUnityFactory,
     IOAuthWebRequestGenerator oAuthWebRequestGenerator,
     IOAuthToken oAuthToken)
 {
     _applicationCredentialsUnityFactory = applicationCredentialsUnityFactory;
     _oAuthWebRequestGenerator           = oAuthWebRequestGenerator;
     _oAuthToken = oAuthToken;
 }
Ejemplo n.º 11
0
 public SampleStream(
     IStreamResultGenerator streamResultGenerator,
     IJsonObjectConverter jsonObjectConverter,
     IJObjectStaticWrapper jObjectStaticWrapper,
     ITweetFactory tweetFactory,
     IOAuthToken oAuthToken)
     : base(streamResultGenerator, jsonObjectConverter, jObjectStaticWrapper, tweetFactory, oAuthToken)
 {
 }
Ejemplo n.º 12
0
        public void OAuthFullTokenExchange()
        {
            // the actual unit under test is GetAccessToken, but we
            // need it so often so it is its own method
            IOAuthToken access_token = testServer.GetAccessToken();

            Assert.That(access_token.Token.Length > 14);
            Assert.That(access_token.Secret.Length > 14);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Authorize a request token
 /// </summary>
 /// <param name="oauthToken">The request token</param>
 public void Authorize(IOAuthToken oauthToken)
 {
     if (oauthToken != null)
     {
         RestClient  restClient = new RestClient(this.OAuthEndpoints.ServiceUri);
         RestRequest request    = new RestRequest(this.OAuthEndpoints.AuthorizationUri);
         request.AddParameter(Constants.TokenParameter, oauthToken.Token);
         var url = restClient.BuildUri(request).ToString();
         Process.Start(url);
     }
 }
Ejemplo n.º 14
0
 public CredentialsCreator(
     IOAuthToken oAuthToken,
     ICredentialsFactory credentialsFactory,
     IOAuthWebRequestGenerator oAuthWebRequestGenerator,
     IUnityFactory <ITemporaryCredentials> applicationCredentialsUnityFactory)
 {
     _oAuthToken                         = oAuthToken;
     _credentialsFactory                 = credentialsFactory;
     _oAuthWebRequestGenerator           = oAuthWebRequestGenerator;
     _applicationCredentialsUnityFactory = applicationCredentialsUnityFactory;
 }
Ejemplo n.º 15
0
 public TweetStream(
     IStreamResultGenerator streamResultGenerator,
     IJsonObjectConverter jsonObjectConverter,
     IJObjectStaticWrapper jObjectStaticWrapper,
     ITweetFactory tweetFactory,
     IOAuthToken oAuthToken)
     : base(streamResultGenerator, jsonObjectConverter, jObjectStaticWrapper)
 {
     _tweetFactory = tweetFactory;
     _oAuthToken   = oAuthToken;
 }
Ejemplo n.º 16
0
        public User GetEntity(IOAuthToken oauthToken, string targetAction)
        {
            User retVal = null;

            if (this.OAuthClient != null)
            {
                string response = this.OAuthClient.ExecuteAuthorizedRequest(this.OAuthClient.OAuthEndpoints.ServiceUri, targetAction, oauthToken);
                retVal = this.DeserializeUser(response);
            }

            return(retVal);
        }
Ejemplo n.º 17
0
        public IList <User> GetCollection(IOAuthToken oauthToken, string targetAction)
        {
            IList <User> retVal = null;

            if (this.OAuthClient != null)
            {
                string response = this.OAuthClient.ExecuteAuthorizedRequest(this.OAuthClient.OAuthEndpoints.ServiceUri, targetAction, oauthToken);
                retVal = this.DeserializeUserList(response);
            }

            return(retVal);
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Gets an entity from the <see cref="IOAuthToken" />.
        /// </summary>
        public static OAuthTokenEntity FromDto(IOAuthToken dto)
        {
            Guard.NotNull(() => dto, dto);

            return(new OAuthTokenEntity
            {
                Id = EntityHelper.SerializeForStorage(dto.Id),
                Username = EntityHelper.SerializeForStorage(dto.Username),
                AccessToken = EntityHelper.SerializeForStorage(dto.AccessToken),
                RefreshToken = EntityHelper.SerializeForStorage(dto.RefreshToken),
                ExpiresOnUtc = EntityHelper.SerializeForStorage(dto.ExpiresOnUtc),
                IssuedOnUtc = EntityHelper.SerializeForStorage(dto.IssuedOnUtc),
            });
        }
Ejemplo n.º 19
0
        public override string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(ERROR_CONSUMER_NULL);
            }

            if (ioAuthToken == null)
            {
                throw new ArgumentNullException(ERROR_TOKEN_NULL);
            }

            var result = string.Format(FORMAT_PARAMETER, OAuthParameter.UrlEncode(consumer.ConsumerSecret), OAuthParameter.UrlEncode(ioAuthToken.TokenSecret));
            return result;
        }
Ejemplo n.º 20
0
        public TrackedStream(
            IStreamTrackManager <ITweet> streamTrackManager,
            IJsonObjectConverter jsonObjectConverter,
            IJObjectStaticWrapper jObjectStaticWrapper,
            IStreamResultGenerator streamResultGenerator,
            ITweetFactory tweetFactory,
            IOAuthToken oAuthToken)

            : base(streamResultGenerator, jsonObjectConverter, jObjectStaticWrapper)
        {
            _streamTrackManager  = streamTrackManager;
            _jsonObjectConverter = jsonObjectConverter;
            _tweetFactory        = tweetFactory;
            _oAuthToken          = oAuthToken;
        }
Ejemplo n.º 21
0
        public WebRequest SignRequest(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken, NameValueCollection additionalParameters, out string oAuthQueryString)
        {
            oAuthQueryString = string.Empty;
            var requestUri = string.Format("{0}://{1}{2}", webRequest.RequestUri.Scheme, webRequest.RequestUri.Authority, webRequest.RequestUri.AbsolutePath);

            var signatureMethod = GetSignatureMethod(consumer.OAuthSignatureMethod);

            //add querystring
            var query = HttpUtility.ParseQueryString(webRequest.RequestUri.Query);
            signatureMethod.RequestParameters.Add(query);

            if (!string.IsNullOrEmpty(ioAuthToken.Openid))
            {
                var openidParms = new NameValueCollection();
                openidParms.Add(OAuthParameter.OPENID,ioAuthToken.Openid);
                signatureMethod.RequestParameters.Add(openidParms);
            }
            //add body content
            signatureMethod.RequestParameters.Add(additionalParameters);

            var signature = signatureMethod.BuildSignature(webRequest, consumer, ioAuthToken);

            signatureMethod.RequestParameters[OAuthParameter.OAUTH_SIGNATURE] = signature;

            switch (consumer.Scheme)
            {
                case AuthorizationSchemeType.Header:
                    var oauthHeader = signatureMethod.ToOAuthHeader();
                    var request1 = WebRequest.Create(requestUri);
                    request1.ContentType = webRequest.ContentType;
                    request1.Headers.Add(OAuthConstants.AUTHORIZATION_HEADER, oauthHeader);
                    request1.Method = webRequest.Method;
                    return request1;
                case AuthorizationSchemeType.QueryString:
                     oAuthQueryString = signatureMethod.ToOAuthQueryString();
                     var request2 = WebRequest.Create(requestUri + "?" + oAuthQueryString);
                    request2.ContentType = webRequest.ContentType;
                    request2.Method = webRequest.Method;

                    return request2;
                case AuthorizationSchemeType.Body:
                    throw new UnSupportedHttpMethodException(webRequest.Method);
                default:
                    throw new ArgumentOutOfRangeException(ARG_SCHEME);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Exchange an request token for an access token
        /// </summary>
        /// <param name="token">The request token</param>
        /// <param name="verifierCode">The verifier code</param>
        /// <returns>An access token and secret</returns>
        public override IOAuthToken ExchangeRequestTokenForAccessToken(IOAuthToken token, string verifierCode)
        {
            DefaultOAuthToken retVal = null;

            if (token != null && !string.IsNullOrEmpty(verifierCode))
            {
                RestClient  restClient = new RestClient(this.OAuthEndpoints.ServiceUri);
                RestRequest request    = new RestRequest(this.OAuthEndpoints.AccessTokenUri);
                restClient.Authenticator = OAuth1Authenticator.ForAccessToken(this.ConsumerKey, this.ConsumerSecret, token.Token, token.Secret, verifierCode);
                var response = restClient.Execute(request);

                var qs = HttpUtility.ParseQueryString(response.Content);
                retVal        = new DefaultOAuthToken();
                retVal.Token  = qs[Constants.TokenParameter];
                retVal.Secret = qs[Constants.TokenSecretParameter];
            }

            return(retVal);
        }
Ejemplo n.º 23
0
        public override string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(ERROR_CONSUMER_NULL);
            }

            if (ioAuthToken == null)
            {
                throw new ArgumentNullException(ERROR_TOKEN_NULL);
            }

            var key = string.Format(FORMAT_PARAMETER, OAuthParameter.UrlEncode(consumer.ConsumerSecret), OAuthParameter.UrlEncode(ioAuthToken.TokenSecret));
            HashAlgorithm hashAlgorithm = new HMACSHA1(Encoding.UTF8.GetBytes(key));
            var encoded = Encoding.UTF8.GetBytes(this.GetCanonicalString(webRequest, consumer, ioAuthToken));
            var result = Convert.ToBase64String(hashAlgorithm.ComputeHash(encoded));

            return result;
        }
Ejemplo n.º 24
0
        // Constructor
        public FilteredStream(
            IStreamTrackManager <ITweet> streamTrackManager,
            IJsonObjectConverter jsonObjectConverter,
            IJObjectStaticWrapper jObjectStaticWrapper,
            IStreamResultGenerator streamResultGenerator,
            ITweetFactory tweetFactory,
            IOAuthToken oAuthToken)

            : base(
                streamTrackManager,
                jsonObjectConverter,
                jObjectStaticWrapper,
                streamResultGenerator,
                tweetFactory,
                oAuthToken)
        {
            _followingUserIds = new Dictionary <long?, Action <ITweet> >();
            _locations        = new Dictionary <ILocation, Action <ITweet> >();
        }
Ejemplo n.º 25
0
        // helper extension method to sign each JSON request with OAuth
        public static void SetAccessToken(this JsonServiceClient client, IOAuthToken access_token)
        {
            // we use a request filter to add the required OAuth header
            client.LocalHttpWebRequestFilter += webservice_request => {

                RequestMethod method = RequestMethod.GET;
                switch (webservice_request.Method) {
                case "GET":
                    method = RequestMethod.GET; break;
                case "POST":
                    method = RequestMethod.POST; break;
                case "DELETE":
                    method = RequestMethod.DELETE; break;
                case "PUT":
                    method = RequestMethod.PUT; break;
                }

                var auth_header = OAuthConnection.GenerateAuthorizationHeader (access_token,
                    webservice_request.RequestUri, method, null);

                webservice_request.Headers ["Authorization"] = auth_header;
            };
        }
Ejemplo n.º 26
0
        public UserStream(
            IStreamResultGenerator streamResultGenerator,
            ITweetFactory tweetFactory,
            IMessageFactory messageFactory,
            IUserFactory userFactory,
            ITweetListFactory tweetListFactory,
            IJObjectStaticWrapper jObjectWrapper,
            IJsonObjectConverter jsonObjectConverter,
            IExceptionHandler exceptionHandler,
            IOAuthToken oAuthToken,
            IStreamTrackManager <ITweet> streamTrackManager)
            : base(streamTrackManager, jsonObjectConverter, jObjectWrapper, streamResultGenerator, tweetFactory, oAuthToken)
        {
            _messageFactory   = messageFactory;
            _userFactory      = userFactory;
            _tweetListFactory = tweetListFactory;
            _jObjectWrapper   = jObjectWrapper;
            _exceptionHandler = exceptionHandler;

            _events = new SortedDictionary <string, Action <JObject> >();

            InitializeEvents();
        }
Ejemplo n.º 27
0
        public override string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException(ERROR_CONSUMER_NULL);
            }

            if (ioAuthToken == null)
            {
                throw new ArgumentNullException(ERROR_TOKEN_NULL);
            }

            var requestUri = string.Format("{0}://{1}{2}", webRequest.RequestUri.Scheme, webRequest.RequestUri.Authority, webRequest.RequestUri.AbsolutePath);
            var request = WebRequest.Create(requestUri);
            request.Method = webRequest.Method;

            var key = string.Format(FORMAT_PARAMETER, OAuthParameter.UrlEncode(consumer.ConsumerSecret), OAuthParameter.UrlEncode(ioAuthToken.TokenSecret));
            HashAlgorithm hashAlgorithm = new HMACSHA1(Encoding.UTF8.GetBytes(key));
            var canonicalString = this.GetCanonicalString(request, consumer, ioAuthToken);
            var encoded = Encoding.UTF8.GetBytes(canonicalString);
            var result = Convert.ToBase64String(hashAlgorithm.ComputeHash(encoded));

            return result;
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Generate the url used to authorize the request token
 /// </summary>
 /// <param name="requestToken">The request token to authorize</param>
 /// <param name="callbackUrl">The callback url</param>
 /// <returns>The ful authorize url</returns>
 public string GetUserAuthorizationUrl(IOAuthToken requestToken)
 {
     return(string.Format("{0}{1}?{2}={3}", this.OAuthEndpoints.ServiceUri, this.OAuthEndpoints.AuthorizationUri, Constants.TokenParameter, requestToken.Token));
 }
Ejemplo n.º 29
0
 public abstract string BuildSignature(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken);
 public DeveloperServiceClient(string serverUrl, IOAuthToken accessToken)
 {
     serverBaseUrl = serverUrl;
     this.accessToken = accessToken;
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Generates a signature using the specified signature type.
        /// </summary>
        /// <param name="url">The full URL that needs to be signed including its non-OAuth URL parameters.</param>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="consumerSecret">The consumer seceret.</param>
        /// <param name="token">The token, if available. If not available pass null or an empty string.</param>
        /// <param name="tokenSecret">The token secret, if available. If not, pass null or an empty string.</param>
        /// <param name="verifier">The callback verifier, if available. If not, pass null or an empty string.</param>
        /// <param name="httpMethod">The HTTP method used. Must be a valid HTTP method verb (POST,GET,PUT, etc).</param>
        /// <param name="signatureType">The type of signature to use.</param>
        /// <returns>A Base64 string of the hash value.</returns>
        private string GenerateSignature(Uri url, string consumerKey, string consumerSecret, IOAuthToken token,
		                                  string verifier, RequestMethod method, TimeSpan timeStamp, string nonce, SignatureType signatureType,
		                                  string callbackUrl, out string normalizedUrl, out List<IQueryParameter<string>> parameters)
        {
            normalizedUrl = null;
            parameters = null;

            switch (signatureType)
            {
                case SignatureType.PLAINTEXT:
                    var signature = UrlEncode (string.Format ("{0}&{1}", consumerSecret, token.Secret));
                    GenerateSignatureBase (url, consumerKey, token, verifier, method, timeStamp, nonce, SignatureType.PLAINTEXT,
                        callbackUrl, out normalizedUrl, out parameters);
                    return signature;
                case SignatureType.HMACSHA1:
            //					string signatureBase = GenerateSignatureBase (url, consumerKey, token, verifier, method,
            //					                                              timeStamp, nonce, SignatureType.HMACSHA1, callbackUrl,
            //					                                              out normalizedUrl, out parameters);
            //
            //					var hmacsha1 = new HMACSHA1 ();
            //					hmacsha1.Key = Encoding.ASCII.GetBytes (string.Format ("{0}&{1}",
            //						UrlEncode (consumerSecret),
            //						string.IsNullOrEmpty (token.Secret) ? "" : UrlEncode(token.Secret)));
            //
            //					var hashedSignature = GenerateSignatureUsingHash (signatureBase, hmacsha1);
            //
            ////					log.LogDebug ("HMAC-SHA1 encoded signature {0} of consumer secret and token secret.", hashedSignature);
            //					return hashedSignature;
                    throw new NotImplementedException ();
            case SignatureType.RSASHA1:
                    throw new NotImplementedException ();
                default:
                    throw new ArgumentException ("Unknown signature type", "signatureType");
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Generates a signature using the HMAC-SHA1 algorithm
        /// </summary>
        /// <param name="url">The full URL that needs to be signed including its non-OAuth URL parameters.</param>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="consumerSecret">The consumer seceret.</param>
        /// <param name="token">The token, if available. If not available pass null or an empty string.</param>
        /// <param name="tokenSecret">The token secret, if available. If not, pass null or an empty string.</param>
        /// <param name="verifier">The callback verifier, if available. If not, pass null or an empty string.</param>
        /// <param name="httpMethod">The HTTP method used. Must be valid HTTP method verb (POST, GET, PUT, etc).</param>
        /// <returns>A Base64 string of the hash value.</returns>
        protected string GenerateSignature(Uri url, string consumerKey, string consumerSecret, IOAuthToken token,
		                                    string verifier, RequestMethod method, TimeSpan timeStamp, string nonce,
		                                    string callbackUrl, out string normalizedUrl,
		                                    out List<IQueryParameter<string>> parameters)
        {
            // TODO use HMACSHA1 instead of PLAINTEXT
            // for non-ssl connection.
            return GenerateSignature (url, consumerKey, consumerSecret, token, verifier, method, timeStamp, nonce,
                                      SignatureType.PLAINTEXT, callbackUrl, out normalizedUrl, out parameters);
        }
Ejemplo n.º 33
0
 public static string GenerateAuthorizationHeader(IOAuthToken accessToken, Uri uri, RequestMethod method, string postData)
 {
     var oauth = new OAuthConnection (uri.ToString());
     oauth.AccessToken = accessToken;
     return oauth.GenerateAuthorizationHeader (uri, method, postData);
 }
Ejemplo n.º 34
0
 public AccessToken(IOAuthConsumer ioAuthConsumer, IOAuthToken ioAuthToken,string openId)
     : base(ioAuthConsumer, ioAuthToken.TokenKey,ioAuthToken.TokenSecret,openId)
 {
     this.TokenType = OAuthTokenType.AccessToken;
 }
Ejemplo n.º 35
0
        protected string GetCanonicalString(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
        {
            if (string.IsNullOrEmpty(webRequest.Method))
            {
                throw new ArgumentNullException(ERROR_HTTP_METHOD);
            }

            var stringToSign = new StringBuilder();
            stringToSign.Append(webRequest.Method.ToUpper().Trim());
            stringToSign.Append(OAuthParameter.QUERYSTRING_SEPERATOR);
            stringToSign.Append(OAuthParameter.UrlEncode(webRequest.RequestUri.AbsoluteUri));
            stringToSign.Append(OAuthParameter.QUERYSTRING_SEPERATOR);

            if (RequestParameters[OAuthParameter.OAUTH_REALM] != null)
                RequestParameters.Remove(OAuthParameter.OAUTH_REALM);

            if (RequestParameters[OAuthParameter.OAUTH_SIGNATURE] != null)
                RequestParameters.Remove(OAuthParameter.OAUTH_SIGNATURE);

            if (RequestParameters[OAuthParameter.OAUTH_SIGNATURE_METHOD] == null)
                RequestParameters.Add(OAuthParameter.OAUTH_SIGNATURE_METHOD, GeneralUtil.SignatureMethodTypeToString(consumer.OAuthSignatureMethod));

            if (RequestParameters[OAuthParameter.OAUTH_CONSUMER_KEY] == null)
                RequestParameters.Add(OAuthParameter.OAUTH_CONSUMER_KEY, consumer.ConsumerKey);

            if (RequestParameters[OAuthParameter.OAUTH_VERSION] == null)
                RequestParameters.Add(OAuthParameter.OAUTH_VERSION, GeneralUtil.OAuthVersionTypeToString(consumer.OAuthVersion));

            if (RequestParameters[OAuthParameter.OAUTH_TIMESTAMP] == null)
                RequestParameters.Add(OAuthParameter.OAUTH_TIMESTAMP, GenerateTimeStamp());
            if (RequestParameters[OAuthParameter.OAUTH_NONCE] == null)
                RequestParameters.Add(OAuthParameter.OAUTH_NONCE, GenerateNonce());
            if (RequestParameters[OAuthParameter.OAUTH_TOKEN] == null && !string.IsNullOrEmpty(ioAuthToken.TokenKey))
                RequestParameters.Add(OAuthParameter.OAUTH_TOKEN, ioAuthToken.TokenKey);

            stringToSign.Append(OAuthParameter.UrlEncode(GetNormalizedParameterString(RequestParameters).Trim()));

            return stringToSign.ToString();
        }
Ejemplo n.º 36
0
 //public RequestToken(IOAuthConsumer ioAuthConsumer, IOAuthToken ioAuthToken)
 //    : this(ioAuthConsumer, ioAuthToken,null)
 //{
 //}
 public RequestToken(IOAuthConsumer ioAuthConsumer, IOAuthToken ioAuthToken, string openId)
     : this(ioAuthConsumer, ioAuthToken,openId, null)
 {
 }
Ejemplo n.º 37
0
 public WebRequest SignRequest(WebRequest webRequest, IOAuthConsumer consumer, IOAuthToken ioAuthToken)
 {
     return this.SignRequest(webRequest, consumer, ioAuthToken);
 }
Ejemplo n.º 38
0
        public string GetAuthorizationUrl(string callbackUrl)
        {
            this.CallbackUrl = callbackUrl;
            GetRootApiRef ();

            var response = Post (apiRoot.OAuthRequestTokenUrl, null, string.Empty);

            if (response.Length == 0) {
                throw new Exception ();
            }

            // Response contains token and token secret.  We only need the token until we're authorized.
            var qs = System.Web.HttpUtility.ParseQueryString (response);
            if (string.IsNullOrEmpty (qs ["oauth_token"])) {
                throw new Exception ("Error reading oauth_token");
            }
            this.RequestToken = new OAuthToken {
                Token = qs ["oauth_token"],
                Secret = qs ["oauth_token_secret"]
            };
            var link = string.Format ("{0}?oauth_token={1}&oauth_callback={2}", apiRoot.OAuthAuthorizeUrl, RequestToken.Token, Uri.EscapeUriString (CallbackUrl));
            return link;
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Exchange a request token and its verifier code for an access token
 /// </summary>y
 /// <param name="requestToken">The request token</param>
 /// <param name="verificationCode">The verification code</param>
 /// <returns>An acces token and its secret</returns>
 public abstract IOAuthToken ExchangeRequestTokenForAccessToken(IOAuthToken requestToken, string verificationCode);
Ejemplo n.º 40
0
        /// <summary>
        /// Generate the signature base that is used to produce the signature
        /// </summary>
        /// <param name="url">The full URL that needs to be signed including its non OAuth URL parameters.</param>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="token">The token, if available. If not available pass null or an empty string.</param>
        /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string.</param>
        /// <param name="verifier">The callback verifier, if available. If not available pass null or an empty string.</param>
        /// <param name="httpMethod">The HTTP method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
        /// <param name="signatureType">The signature type. To use the default values use <see cref="SignatureType">SignatureType</see>.</param>
        /// <returns>The signature base.</returns>
        private string GenerateSignatureBase(Uri url, string consumerKey, IOAuthToken token, string verifier,
						      RequestMethod method, TimeSpan timeStamp, string nonce, SignatureType signatureType, string callbackUrl,
						      out string normalizedUrl,
			out List<IQueryParameter<string>> parameters)
        {
            token.Token = token.Token ?? string.Empty;
            token.Secret = token.Secret ?? string.Empty;
            verifier = verifier ?? String.Empty;

            if (consumerKey == null) throw new ArgumentNullException ("consumerKey");

            var signatureString = string.Empty;

            switch (signatureType) {
                case SignatureType.HMACSHA1:
                    signatureString = "HMAC-SHA1";
                    break;
                case SignatureType.RSASHA1:
                    signatureString = "RSA-SHA1";
                    break;
                case SignatureType.PLAINTEXT:
                    signatureString = SignatureType.PLAINTEXT.ToString ();
                    break;
            }

            parameters = GetQueryParameters (url.Query).Concat (new List<IQueryParameter<string>> {
                new QueryParameter<string> (OAuthVersionKey, OAuthVersion, s => string.IsNullOrEmpty (s)),
                new QueryParameter<string> (OAuthTimestampKey, ((long)timeStamp.TotalSeconds).ToString (), s => string.IsNullOrEmpty (s)),
                new QueryParameter<string> (OAuthSignatureMethodKey, signatureString, s => string.IsNullOrEmpty (s)),
                new QueryParameter<string> (OAuthNonceKey, nonce, s => string.IsNullOrEmpty (s)),
                new QueryParameter<string> (OAuthConsumerKeyKey, consumerKey, s => string.IsNullOrEmpty (s))
            }).ToList ();

            if (!string.IsNullOrEmpty (token.Token)) parameters.Add (new QueryParameter<string> (OAuthTokenKey, token.Token, s => string.IsNullOrEmpty (s)));
            if (!string.IsNullOrEmpty (verifier)) parameters.Add (new QueryParameter<string> (OAuthVerifierKey, verifier, s => string.IsNullOrEmpty (s)));
            if (!string.IsNullOrEmpty (callbackUrl)) parameters.Add (new QueryParameter<string> (OAuthCallbackKey, UrlEncode (callbackUrl), s => string.IsNullOrEmpty (s)));

            normalizedUrl = string.Format ("{0}://{1}", url.Scheme, url.Host);
            if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) normalizedUrl += ":" + url.Port;
            normalizedUrl += url.AbsolutePath;

            parameters.Sort ();
            string normalizedRequestParameters = parameters.NormalizeRequestParameters ();

            var signatureBase = new StringBuilder ();
            signatureBase.AppendFormat("{0}&", method.ToString ());
            signatureBase.AppendFormat("{0}&", UrlEncode (normalizedUrl));
            signatureBase.AppendFormat("{0}", UrlEncode (normalizedRequestParameters));

            return signatureBase.ToString ();
        }
Ejemplo n.º 41
0
 public AccessToken(IOAuthConsumer ioAuthConsumer, IOAuthToken ioAuthToken)
     : this(ioAuthConsumer, ioAuthToken, ioAuthToken.Openid)
 {
 }
Ejemplo n.º 42
0
 public RequestToken(IOAuthConsumer ioAuthConsumer, IOAuthToken ioAuthToken,string openId, bool? callbackConfirmed)
     : base(ioAuthConsumer, ioAuthToken.TokenKey, ioAuthToken.TokenSecret,openId,callbackConfirmed)
 {
     this.TokenType = OAuthTokenType.RequestToken;
 }