Beispiel #1
0
        public void GetSignatureForTokenCredentials()
        {
            // Arrange
            const string expected             = "gKgrFCywp7rO0OXSjdot/IHF7IU=";
            var          clientCredentials    = new OAuthCredential("dpf43f3p2l4k3l03", "kd94hf93k423kf44");
            var          temporaryCredentials = new OAuthCredential("hh5s93j4hdidpola", "hdhd0244k9j7ao03");
            var          uri        = new Uri("https://photos.example.net/token");
            var          parameters = new Dictionary <string, StringValues>
            {
                [OAuthDefaults.Realm]                = "Photos",
                [OAuthDefaults.OAuthConsumerKey]     = clientCredentials.Key,
                [OAuthDefaults.OAuthToken]           = temporaryCredentials.Key,
                [OAuthDefaults.OAuthSignatureMethod] = _signer.MethodName,
                [OAuthDefaults.OAuthTimestamp]       = "137131201",
                [OAuthDefaults.OAuthNonce]           = "walatlh",
                [OAuthDefaults.OAuthVerifier]        = "hfdp7dh39dks9884",
                [OAuthDefaults.OAuthSignature]       = expected
            };

            // Act
            var actual = _signer.GetSignature(HttpMethod.Post, uri,
                                              parameters, clientCredentials.Secret, temporaryCredentials.Secret);

            // Assert
            Assert.Equal(expected, actual);
        }
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();

            if (args.Length < 5) {
                Console.WriteLine("Usage: GetAuthorizedToken.exe api_url consumer_key " +
                    "consumer_secret request_token " +
                    "request_token_secret");
                return;
            }

            string apiUrl = args[0];
            string consumerKey = args[1];
            string consumerSecret = args[2];
            string requestToken = args[3];
            string requestTokenSecret = args[4];

            Credential credential = new OAuthCredential(
                consumerKey, consumerSecret,
                requestToken, requestTokenSecret);

            TripIt t = new TripIt(credential, apiUrl);

            OAuthCredential authorizedCredential = t.GetAccessToken();

            Console.WriteLine("Authorized Token: " + authorizedCredential.Token);
            Console.WriteLine("Token Secret:     " + authorizedCredential.TokenSecret);
        }
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();

            if (args.Length < 5) {
                Console.WriteLine("Usage: Example.exe api_url consumer_key " +
                    "consumer_secret authorized_token " +
                    "authorized_token_secret");
                return;
            }

            string apiUrl = args[0];
            string consumerKey = args[1];
            string consumerSecret = args[2];
            string authorizedToken = args[3];
            string authorizedTokenSecret = args[4];

            Credential credential = new OAuthCredential(
                consumerKey, consumerSecret,
                authorizedToken, authorizedTokenSecret);

            TripIt t = new TripIt(credential, apiUrl);

            Console.WriteLine(t.ListTrip().Trip.Length);
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();

            if (args.Length < 5)
            {
                Console.WriteLine("Usage: Example.exe api_url consumer_key " +
                                  "consumer_secret authorized_token " +
                                  "authorized_token_secret");
                return;
            }

            string apiUrl                = args[0];
            string consumerKey           = args[1];
            string consumerSecret        = args[2];
            string authorizedToken       = args[3];
            string authorizedTokenSecret = args[4];

            Credential credential = new OAuthCredential(
                consumerKey, consumerSecret,
                authorizedToken, authorizedTokenSecret);

            TripIt t = new TripIt(credential, apiUrl);

            Console.WriteLine(t.ListTrip().Trip.Length);
        }
Beispiel #5
0
        protected void ValidateOAuth3rdLoginRequest(OAuthService provider, IOAuthTokenPost dataPost)
        {
            if (!OAuth.IsRequestToken)
            {
                throw new HttpBadRequestException(
                          "106 " + ControllerStrings.Warning106_RequestTokenRequired
                          );
            }

            this.OAuth3rdCredential =
                Database.OAuthCredentialStore.GetFirst(
                    filter: f =>
                    f.OAuthProvider == provider &&
                    f.Uid == dataPost.ID,
                    include:
                    new string[] { "User" }
                    );

            if (this.OAuth3rdCredential == null)
            {
                OAuth.Token.LoginAttempts++;
                Database.TokenStore.Update(OAuth.Token);
                Database.SaveChanges();

                throw new HttpNotFoundException(
                          "105 " + ControllerStrings.Warning105_SocialTokenNotFound
                          );
            }
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();

            if (args.Length < 5)
            {
                Console.WriteLine("Usage: GetAuthorizedToken.exe api_url consumer_key " +
                                  "consumer_secret request_token " +
                                  "request_token_secret");
                return;
            }

            string apiUrl             = args[0];
            string consumerKey        = args[1];
            string consumerSecret     = args[2];
            string requestToken       = args[3];
            string requestTokenSecret = args[4];

            Credential credential = new OAuthCredential(
                consumerKey, consumerSecret,
                requestToken, requestTokenSecret);

            TripIt t = new TripIt(credential, apiUrl);

            OAuthCredential authorizedCredential = t.GetAccessToken();

            Console.WriteLine("Authorized Token: " + authorizedCredential.Token);
            Console.WriteLine("Token Secret:     " + authorizedCredential.TokenSecret);
        }
Beispiel #7
0
        /// <summary>
        /// Save an oAuth Credential
        /// </summary>
        /// <param name="credential"></param>
        /// <returns></returns>
        public async Task <OAuthCredential> SaveOAuthCredentialAsync(OAuthCredential credential, IUserContext userContext)
        {
            await _dataLock.WaitAsync();

            try
            {
                credential.UserId = userContext?.UserId;
                var existingCredential = _db.OAuthCredentials.Where(x => x.Provider == credential.Provider && x.UserId == credential.UserId).FirstOrDefault();
                if (existingCredential != null)
                {
                    existingCredential.AccessToken  = credential.AccessToken;
                    existingCredential.RefreshToken = credential.RefreshToken;
                }
                else
                {
                    _db.OAuthCredentials.Add(credential);
                }
                _isDirty = true;
            }
            finally
            {
                _dataLock.Release();
            }
            return(credential);
        }
Beispiel #8
0
        public IHttpActionResult TwitterAdd([FromBody] OAuth3rdLoginPost dataPost)
        {
            ValidateOAuth3rdAddRequest(OAuthService.Twitter, dataPost);
            var twitterClient = OAuth3rdClient <TwitterClient>(dataPost);

            OAuthCredential twitterCredential;

            try {
                twitterCredential = new OAuthCredential {
                    OAuthProvider = OAuthService.Twitter,
                    Uid           = twitterClient.UserID,
                    Token         = twitterClient.Token.Key,
                    Secret        = twitterClient.Token.Secret,
                    IsInvalid     = false,

                    User = CurrentUser
                };
            } catch (OAuthUnexpectedResponse ex) {
                throw new HttpNotFoundException(
                          "105 " + ControllerStrings.Warning105_SocialTokenNotFound,
                          ex
                          );
            }

            Database.OAuthCredentialStore.Add(twitterCredential);
            Database.SaveChanges();

            return(Ok());
        }
Beispiel #9
0
        public IHttpActionResult FacebookAdd([FromBody] OAuthFacebookLoginPost dataPost)
        {
            ValidateOAuth3rdAddRequest(OAuthService.Facebook, dataPost);
            var facebookClient = OAuth3rdClient <FacebookClient>(dataPost);

            OAuthCredential facebookCredential;

            try {
                facebookClient.ExchangeCodeForToken(dataPost.Code);

                facebookCredential = new OAuthCredential {
                    OAuthProvider = OAuthService.Facebook,
                    Uid           = facebookClient.UserID,
                    Token         = facebookClient.Token.Key,
                    IsInvalid     = false,

                    User = CurrentUser
                };
            } catch (OAuthUnexpectedResponse ex) {
                throw new HttpNotFoundException(
                          "105 " + ControllerStrings.Warning105_SocialTokenNotFound,
                          ex
                          );
            }

            Database.OAuthCredentialStore.Add(facebookCredential);
            Database.SaveChanges();

            return(Ok());
        }
Beispiel #10
0
 public static IAuthCredential Create(AuthCredential authCredential)
 {
     return(authCredential switch
     {
         OAuthCredential oAuthCredential => new OAuthCredentialWrapper(oAuthCredential),
         PhoneAuthCredential phoneAuthCredential => new PhoneAuthCredentialWrapper(phoneAuthCredential),
         _ => new AuthCredentialWrapper(authCredential)
     });
 public TwitterConnector()
 {
     _creds = new OAuthCredential(consumerKey)
     {
         Token = token
     };
     _signatureEntity = new OAuthSignatureEntity(consumerSecret)
     {
         TokenSecret = tokenSecret
     };
 }
Beispiel #12
0
 public OAuthHttpClientTests(OAuthFixture fixture)
 {
     _configuration    = fixture.Configuration;
     _tokenCredentials = new OAuthCredential(
         _configuration["OAuth:TokenId"],
         _configuration["OAuth:TokenSecret"]);
     if (_configuration.GetValue("HttpClient:Mock", true))
     {
         _mockHttp = new MockHttpMessageHandler();
         _mockHttp.Fallback.Respond(HttpStatusCode.Unauthorized);
     }
 }
        public async Task <OAuthCredential> SaveOAuthCredentialAsync(OAuthCredential credential, IUserContext userContext)
        {
            credential.UserId = userContext?.UserId;
            var query  = @"SELECT Provider FROM OAuthCredentials WHERE Provider = @Provider AND (@UserId IS NULL OR UserId = @UserId);";
            var result = await SqlQueryAsync <OAuthCredential>(query, credential);

            if (result.Any())
            {
                query = $@"UPDATE OAuthCredentials SET AccessToken = @AccessToken, RefreshToken = @RefreshToken, DateCreatedUtc = @DateCreatedUtc, DateExpiresUtc = @DateExpiresUtc WHERE Provider = @Provider AND (@UserId IS NULL OR UserId = @UserId);";
                await ExecuteAsync <object>(query, credential);
            }
            else
            {
                query =
                    $@"INSERT INTO OAuthCredentials (Provider, AccessToken, RefreshToken, DateCreatedUtc, DateExpiresUtc, UserId) 
VALUES (@Provider, @AccessToken, @RefreshToken, @DateCreatedUtc, @DateExpiresUtc, @UserId);";
                await InsertAsync <OAuthCredential, string>(query, credential, (x, key) => { });
            }
            return(credential);
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();

            if (args.Length < 5)
            {
                Console.WriteLine("Usage: MakePostRequest.exe api_url consumer_key " +
                                  "consumer_secret authorized_token " +
                                  "authorized_token_secret");
                return;
            }

            string apiUrl                = args[0];
            string consumerKey           = args[1];
            string consumerSecret        = args[2];
            string authorizedToken       = args[3];
            string authorizedTokenSecret = args[4];

            Credential credential = new OAuthCredential(
                consumerKey, consumerSecret,
                authorizedToken, authorizedTokenSecret);

            TripIt t = new TripIt(credential, apiUrl);

            string tripXml = "<Request><Trip>" +
                             "<start_date>2009-12-09</start_date>" +
                             "<end_date>2009-12-27</end_date>" +
                             "<primary_location>New York, NY</primary_location>" +
                             "</Trip></Request>";
            string tripXml2 = "<Request><Trip>" +
                              "<start_date>2010-12-09</start_date>" +
                              "<end_date>2010-12-27</end_date>" +
                              "<primary_location>Boston, MA</primary_location>" +
                              "</Trip></Request>";

            TravelObject.Response response = t.Create(tripXml);
            int id = int.Parse(response.Trip[0].id);

            Console.WriteLine(id);
            t.ReplaceTrip(id, tripXml2);
        }
Beispiel #15
0
        protected void ValidateOAuth3rdAddRequest(OAuthService provider, IOAuthTokenPost dataPost)
        {
            this.OAuth3rdCredential =
                Database.OAuthCredentialStore.GetFirst(
                    filter: f =>
                    f.OAuthProvider == provider &&
                    f.Uid == dataPost.ID
                    );

            if (this.OAuth3rdCredential == null)
            {
                return;
            }

            if (this.OAuth3rdCredential.User != null && this.OAuth3rdCredential.User.Guid != CurrentUser.Guid)
            {
                throw new HttpConflictException(
                          "109 " + ControllerStrings.Warning109_SocialTokenAlreadyInUse
                          );
            }
        }
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatesPolicy();

            if (args.Length < 5) {
                Console.WriteLine("Usage: MakePostRequest.exe api_url consumer_key " +
                    "consumer_secret authorized_token " +
                    "authorized_token_secret");
                return;
            }

            string apiUrl = args[0];
            string consumerKey = args[1];
            string consumerSecret = args[2];
            string authorizedToken = args[3];
            string authorizedTokenSecret = args[4];

            Credential credential = new OAuthCredential(
                consumerKey, consumerSecret,
                authorizedToken, authorizedTokenSecret);

            TripIt t = new TripIt(credential, apiUrl);

            string tripXml = "<Request><Trip>" +
                "<start_date>2009-12-09</start_date>" +
                "<end_date>2009-12-27</end_date>" +
                "<primary_location>New York, NY</primary_location>" +
                "</Trip></Request>";
            string tripXml2 = "<Request><Trip>" +
                "<start_date>2010-12-09</start_date>" +
                "<end_date>2010-12-27</end_date>" +
                "<primary_location>Boston, MA</primary_location>" +
                "</Trip></Request>";

            TravelObject.Response response = t.Create(tripXml);
            int id = int.Parse(response.Trip[0].id);
            Console.WriteLine(id);
            t.ReplaceTrip(id, tripXml2);
        }
Beispiel #17
0
        public void GetSignatureForResource()
        {
            // Arrange
            const string expected          = "MdpQcU8iPSUjWoN/UDMsK2sui9I=";
            var          clientCredentials = new OAuthCredential("dpf43f3p2l4k3l03", "kd94hf93k423kf44");
            var          tokenCredentials  = new OAuthCredential("nnch734d00sl2jdk", "pfkkdhi9sl3r4s00");
            var          uri = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original");

            var parameters = QueryHelpers.ParseQuery(uri.Query);

            parameters[OAuthDefaults.OAuthConsumerKey]     = clientCredentials.Key;
            parameters[OAuthDefaults.OAuthToken]           = tokenCredentials.Key;
            parameters[OAuthDefaults.OAuthNonce]           = "chapoH";
            parameters[OAuthDefaults.OAuthTimestamp]       = "137131202";
            parameters[OAuthDefaults.OAuthSignatureMethod] = _signer.MethodName;

            // Act
            var actual = _signer.GetSignature(HttpMethod.Get, uri,
                                              parameters, clientCredentials.Secret, tokenCredentials.Secret);

            // Assert
            Assert.Equal(expected, actual);
        }
Beispiel #18
0
        public void AddNamedOAuthHttpClient_WithCustomConfigureOptions_ShouldAddInServiceProvider()
        {
            // Arrange
            var baseAddress       = new Uri("http://example.com");
            var clientCredentials = new OAuthCredential(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString());
            var tokenCredentials  = new OAuthCredential(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString());
            var collection        = new ServiceCollection();
            var services          = collection.AddOAuthHttpClient <DemoOptions>("client1", (_, options) =>
            {
                options.BaseAddress       = baseAddress;
                options.ClientCredentials = clientCredentials;
                options.TokenCredentials  = tokenCredentials;
            }).Services.BuildServiceProvider();

            // Act
            var actual = services.GetService <IOptions <DemoOptions> >()?.Value;

            // Assert
            Assert.Equal(baseAddress, actual?.BaseAddress);
            Assert.Equal(clientCredentials.Key, actual?.ClientCredentials.Key);
            Assert.Equal(clientCredentials.Secret, actual?.ClientCredentials.Secret);
            Assert.Equal(tokenCredentials.Key, actual?.TokenCredentials.Key);
            Assert.Equal(tokenCredentials.Secret, actual?.TokenCredentials.Secret);
        }
Beispiel #19
0
        public void GetSignatureForTemporaryCredentials()
        {
            // Arrange
            const string expected          = "74KNZJeDHnMBp0EMJ9ZHt/XKycU=";
            var          clientCredentials = new OAuthCredential("dpf43f3p2l4k3l03", "kd94hf93k423kf44");
            var          uri        = new Uri("https://photos.example.net/initiate");
            var          parameters = new Dictionary <string, StringValues>
            {
                [OAuthDefaults.Realm]                = "Photos",
                [OAuthDefaults.OAuthConsumerKey]     = clientCredentials.Key,
                [OAuthDefaults.OAuthSignatureMethod] = _signer.MethodName,
                [OAuthDefaults.OAuthTimestamp]       = "137131200",
                [OAuthDefaults.OAuthNonce]           = "wIjqoS",
                [OAuthDefaults.OAuthCallback]        = "http://printer.example.com/ready",
                [OAuthDefaults.OAuthSignature]       = expected
            };

            // Act
            var actual = _signer.GetSignature(HttpMethod.Post, uri,
                                              parameters, clientCredentials.Secret);

            // Assert
            Assert.Equal(expected, actual);
        }
Beispiel #20
0
 /// <summary>
 /// Save an oAuth Credential
 /// </summary>
 /// <param name="credential"></param>
 /// <returns></returns>
 public async Task <OAuthCredential> SaveOAuthCredentialAsync(OAuthCredential credential)
 {
     return(await _storageProvider.SaveOAuthCredentialAsync(credential, _requestContext.GetUserContext()));
 }
Beispiel #21
0
 public OAuthCredentialWrapper(OAuthCredential oAuthCredential) : base(oAuthCredential)
 {
     _oAuthCredential = oAuthCredential ?? throw new ArgumentNullException(nameof(oAuthCredential));
 }