Beispiel #1
0
        public Account ProcessAuthentication(string pin)
        {
            TwitterService service = new TwitterService(_consumerKey, _consumerSecret);

            OAuthAccessToken access = service.GetAccessToken(_requestToken, pin);

            service.AuthenticateWith(access.Token, access.TokenSecret);

            var profile = service.GetUserProfile();

            Account account = AccountManager.Instance.GetCurrentAccounts().Where(acc => acc.Username == profile.ScreenName).FirstOrDefault();
            if (account != null)
            {
                throw new AuthFailureException("User " +account.Username +  " already has an account with TweetOBox.");
            }
            if (profile != null && account == null)
            {
                account = new Account();
                account.Username = profile.ScreenName;
               // account.Password = profile.p
                account.AccountType = (int)AccountTypeEnum.Twitter;
                account.AccessToken = access.Token;
                account.AccessTokenSecret = access.TokenSecret;
                account.IsOAuth = true;
                AccountManager.Instance.AddAccount(account,false);
            }
            else
            {
                throw new AuthFailureException(service.Response.StatusDescription);
            }

            return account;
        }
Beispiel #2
0
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();

            // Disable keep alive, no need
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromMinutes(3);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ShootR",
                Provider = new ShootRAuthenticationProvider()
            });

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                Provider = new TwitterAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        var service = new TwitterService(ConfigurationManager.AppSettings["twitterConsumerKey"], ConfigurationManager.AppSettings["twitterConsumerSecret"]);
                        service.AuthenticateWith(context.AccessToken, context.AccessTokenSecret);

                        var profile = service.GetUserProfile(new GetUserProfileOptions
                        {
                            IncludeEntities = true
                        });

                        context.Identity.AddClaim(new Claim("profilePicture", profile.ProfileImageUrl));
                    }
                },
                SignInAsAuthenticationType = "ShootR",
                ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
            });

            app.UseGoogleAuthentication(new GoogleAuthenticationOptions
            {
                SignInAsAuthenticationType = "ShootR"
            });

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("profilePicture", "https://graph.facebook.com/" + context.Identity.FindFirst(ClaimTypes.NameIdentifier).Value + "/picture?type=large"));
                    }
                },
                SignInAsAuthenticationType = "ShootR",
                AppId = ConfigurationManager.AppSettings["facebookAppId"],
                AppSecret = ConfigurationManager.AppSettings["facebookAppSecret"]
            });
        }
        public TokenData Get(IpData data)
        {
            // Pass your credentials to the service
            string consumerKey = _settings.TwitterConsumerKey;
            string consumerSecret = _settings.TwitterConsumerSecret;

            // Try to validate token
            var service = new TwitterService(consumerKey, consumerSecret);
            service.AuthenticateWith(data.Token, data.TokenSecret);

            TwitterUser user = service.GetUserProfile(new GetUserProfileOptions());
            if (user != null)
            {
                return new TokenData
                {
                    IdentityProvider = ProviderType.Twitter,
                    Name = user.Name,
                    UserIdentifier = string.Format(TwitterAccountPage, user.Id),
                    Token = data.Token,
                    TokenSecret = data.TokenSecret
                };
            }

            // Check response status code
            switch (service.Response.StatusCode)
            {
                case HttpStatusCode.Unauthorized:
                case HttpStatusCode.BadRequest:
                    throw new BadRequestException();

                case (HttpStatusCode)429:
                    throw new TooManyRequestsException();
            }

            // Twitter internal errors
            if ((int)service.Response.StatusCode >= 500)
            {
                throw new BadGatewayException(service.Response.Response);
            }

            string message = string.Format("Unable to receive twitter profile. Status code {0}: {1}", service.Response.StatusCode, service.Response.InnerException);
            throw new InternalServerErrorException(message);
        }
        public string GetResponseHtml(IDictionary<string, string> parameters, Uri signinUri)
        {
            var requestToken = new OAuthRequestToken { Token = parameters["oauth_token"] };

            // Exchange the Request Token for an Access Token
            string consumerKey = _settings.TwitterConsumerKey;
            string consumerSecret = _settings.TwitterConsumerSecret;

            var service = new TwitterService(consumerKey, consumerSecret);

            OAuthAccessToken accessToken = service.GetAccessToken(requestToken, parameters["oauth_verifier"]);
            service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);

            TwitterUser user = service.GetUserProfile(new GetUserProfileOptions());

            // Claims
            string name = user != null ? user.Name : accessToken.ScreenName;
            string nameIdentifier = string.Format(TwitterAccountPage, accessToken.UserId);
            string token = accessToken.Token;
            string tokenSecret = accessToken.TokenSecret;

            string acsNamespace = _settings.AcsNamespace;

            string wtRealm = string.Format(WtRealm, acsNamespace);
            string wReply = string.Format(WReply, acsNamespace);

            var requestMessage = new SignInRequestMessage(signinUri, wtRealm, wReply);

            // Add extracted claims
            var identity = new ClaimsIdentity(AuthenticationTypes.Federation);
            identity.AddClaim(new Claim(ClaimTypes.Name, name));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, nameIdentifier));
            identity.AddClaim(new Claim(TwitterClaims.TwitterToken, token));
            identity.AddClaim(new Claim(TwitterClaims.TwitterTokenSecret, tokenSecret));

            var principal = new ClaimsPrincipal(identity);

            SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, principal, this);
            responseMessage.Context = parameters["context"];

            return responseMessage.WriteFormPost();
        }
Beispiel #5
0
        public Account Authenticate(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName) || String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("userName");
            }

            TwitterService service = new TwitterService(ConfigurationManager.AppSettings["ConsumerKey"],
                ConfigurationManager.AppSettings["ConsumerSecret"]);

            OAuthAccessToken access = service.GetAccessTokenWithXAuth(userName, password);

            service.AuthenticateWith(access.Token, access.TokenSecret);

            var profile = service.GetUserProfile();

            Account account = AccountManager.Instance.GetCurrentAccounts().Where(acc => acc.Username == profile.ScreenName).FirstOrDefault();
            if (account != null)
            {
                throw new AuthFailureException("User " + account.Username + " already has an account with TweetOBox.");
            }
            if (profile != null && account == null)
            {
                account = new Account();
                account.Username = profile.ScreenName;
                // account.Password = profile.p
                account.AccountType = (int)AccountTypeEnum.Twitter;
                account.AccessToken = access.Token;
                account.AccessTokenSecret = access.TokenSecret;
                account.IsOAuth = true;
                AccountManager.Instance.AddAccount(account, false);
            }
            else
            {
                throw new AuthFailureException(service.Response.StatusDescription);
            }

            return account;
        }
        static void Main(string[] args)
        {
            //This app's unique Consumer Key (first argument) and Consumer Secret (second argument)
            TwitterService t_serv = new TwitterService("agvQyQIx2FFciJSpgCSwQ", "vdmcbG4EHveIQPA65WWzW1KYRFFFZY2B7MWFf2BHXqc");

            // Use this app's consumer info (consumer key and consumer secret) to get request token
            OAuthRequestToken r_token = t_serv.GetRequestToken();
            
            // Use request token and send user to Twitter to get a PIN
            Uri uri_1 = t_serv.GetAuthorizationUri(r_token); // get authorization URI using request token
            Process.Start(uri_1.ToString()); // 

            // Take in PIN and generate an access token and secret
            Console.WriteLine("Please enter the PIN number you received from Twitter: ");
            string ver_num = Console.ReadLine();
            OAuthAccessToken a_token = t_serv.GetAccessToken(r_token, ver_num);

            // Console.WriteLine("The PIN you entered was " + ver_num + ".");
            
            // authenticate using the access token and secret
            t_serv.AuthenticateWith(a_token.Token, a_token.TokenSecret);

            // get the tweets on the user's public timeline
            string user_sn = t_serv.GetUserProfile().ScreenName;

            Console.WriteLine("user id: " + user_sn);
            /*
            foreach (var tweet in lastTweets)
            {
                Console.WriteLine("{0} says {1}", tweet.User.ScreenName, tweet.Text);
            }
            */
           
            // step 4: save user data in a database

            // step 5: display database info in a webpage

            Console.ReadKey(true);
        }
        /// <summary>
        ///     Gets an user profile information.
        /// </summary>
        /// <param name="request">Request message.</param>
        /// <returns>User profile.</returns>
        public TwitterProfile GetProfile(TwitterRequest request)
        {
            // Pass your credentials to the service
            string consumerKey = _settings.TwitterConsumerKey;
            string consumerSecret = _settings.TwitterConsumerSecret;

            // Authorize
            var service = new TwitterService(consumerKey, consumerSecret);
            service.AuthenticateWith(request.Token, request.TokenSecret);

            // Get user info
            TwitterUser user = service.GetUserProfile(new GetUserProfileOptions());
            if (user != null)
            {
                return new TwitterProfile
                {
                    Id = user.Id,
                    ImageUrl = user.ProfileImageUrl,
                    Name = user.Name,
                    ScreenName = user.ScreenName
                };
            }

            // Check response status code
            switch (service.Response.StatusCode)
            {
                case HttpStatusCode.Unauthorized:
                case HttpStatusCode.BadRequest:
                    // Invalid credentials or request data
                    throw new BadRequestException(service.Response.Response);

                case (HttpStatusCode)429:
                    throw new TooManyRequestsException(service.Response.Response);
            }

            // Twitter internal errors
            if ((int)service.Response.StatusCode >= 500)
            {
                throw new BadGatewayException(service.Response.Response);
            }

            string message = string.Format("Unable to receive twitter profile. Status code {0}: {1}", service.Response.StatusCode, service.Response);
            throw new InternalServerErrorException(message);
        }
        private async Task DownloadTwitterProfileImage(IEnumerable<Claim> claims, string userId)
        {
            // Retrieve the twitter access token and claim
            var accessTokenClaim = claims.FirstOrDefault(x => x.Type == Startup.TwitterAccessTokenClaimType);
            var accessTokenSecretClaim = claims.FirstOrDefault(x => x.Type == Startup.TwitterAccessTokenSecretClaimType);

            if (accessTokenClaim != null && accessTokenSecretClaim != null)
            {
                // Initialize the Twitter client
                var service = new TwitterService(
                    Startup.TwitterConsumerKey,
                    Startup.TwitterConsumerSecret,
                    accessTokenClaim.Value,
                    accessTokenSecretClaim.Value
                    );

                var profile = service.GetUserProfile(new GetUserProfileOptions());
                if (profile != null && !String.IsNullOrWhiteSpace(profile.ProfileImageUrlHttps))
                {
                    string filename = Server.MapPath(string.Format("~/ProfileImages/{0}.jpeg", userId));

                    await DownloadProfileImage(new Uri(profile.ProfileImageUrlHttps), filename);
                }
            }
        }
        /// <summary>
        /// Retreive the url of the Connected Twitter Users's profile picture
        /// </summary>
        /// <param name="accessToken">Twitter user's Access Token</param>
        /// <param name="accessTokenSecret">Twitter user's Access Token Secret</param>
        /// <returns>Url of the Twitter Users's profile picture</returns>
        private string GetTwitterProfileImage(string accessToken, string accessTokenSecret)
        {
            if (accessToken != null && accessTokenSecret != null)
            {
                // Initialize the Twitter client
                var service = new TwitterService(
                    ConfigurationManager.AppSettings["TwitterConsumerKey"],
                    ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                    accessToken,
                    accessTokenSecret
                    );
                var profile = service.GetUserProfile(new GetUserProfileOptions());

                if (profile != null && !String.IsNullOrWhiteSpace(profile.ProfileImageUrlHttps))
                {
                    return profile.ProfileImageUrlHttps;
                }
                return "";
            }
            return null;
        }
        public ChannelSocialProfile GetProfile()
        {
            var service = new TwitterService(ChannelHelper.ConsumerKey, ChannelHelper.ConsumerSecret, ChannelHelper.Token, ChannelHelper.TokenSecret);
            var result = service.GetUserProfile();

            return new ChannelSocialProfile
                {
                    Id = result.Id.ToString(),
                    FullName = result.Name,
                    AvatarUrl = result.ProfileImageUrl
                };
        }
Beispiel #11
0
 public async Task<ActionResult> TwitterLoginCallBack(string object_id, string access_token, string access_token_secret, string tw_key)
 {
     bool success = false;
     var twLoginInfo = new UserLoginInfo("Twitter", tw_key);
     MyUser my_user = await UserManager.FindByIdAsync(object_id);
     if (my_user != null)
     {
         success = SetCurrentUser(AuthType.Twitter, my_user, access_token, access_token_secret);
         return Json(new { OK = success });  
     }
     var tw_service = new TwitterService
     (
         consumerKey: ExternalAuthManaher.TwitterService.AppID,
         consumerSecret: ExternalAuthManaher.TwitterService.AppSecret,
         token: access_token,
         tokenSecret: access_token_secret
     );
     var userInfo =  tw_service.GetUserProfile(new GetUserProfileOptions());
     if(userInfo != null)
     {
         
         success = await RegisterUser(
              new RegisterUserModel
              {
                  RegisterType = AuthType.Twitter,
                  LoginProvider = twLoginInfo,
                  UserClaims = new List<Claim> 
                     {
                         new Claim("TwitterAccessToken", access_token),
                         new Claim("TwitterAccessTokenSecret", access_token_secret),
                         new Claim("TwitterPageLink", ("https://twitter.com/" + userInfo.ScreenName)),
                         new Claim("TwitterId", userInfo.Id.ToString()),
                         new Claim("Photo", userInfo.ProfileImageUrl)
                     },
                  Name = userInfo.ScreenName,
                  Login = "******",
                  Object_id = object_id
              });
         return Json(new { OK = success }); 
     }
     return Json(new { OK = false });  
 }
        /// <summary>
        /// Returns the current user (fails if there is no status yet)
        /// Missing method in TweetSharp
        /// </summary>
        /// <returns>the current Twitter User</returns>
        internal TwitterUser GetStats()
        {
            var service = new TwitterService(ClientInfo);
            service.AuthenticateWith(Token, TokenSecret);

            LastResponse = service.Response;
            return service.GetUserProfile();
        }
Beispiel #13
0
 public Task<TwitterUser> GetWebData(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret)
 {
     var service = new TwitterService(consumerKey, consumerSecret);
     service.AuthenticateWith(accessToken, accessTokenSecret);
     return Task.FromResult(service.GetUserProfile(new GetUserProfileOptions()));
 }
        /// <summary>
        /// Source: http://www.jerriepelser.com/blog/get-the-twitter-profile-image-using-the-asp-net-identity
        /// https://github.com/jerriep/AspNetIdentitySocialProfileImage/blob/master/Controllers/AccountController.cs
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private async Task DownloadTwitterProfileImage(string userId)
        {
            var identity = (ClaimsIdentity)User.Identity;
            IEnumerable<Claim> claims = identity.Claims;

            if (claims != null)
            {
                // Retrieve the twitter access token and claim
                var accessTokenClaim = claims.FirstOrDefault(x => x.Type == TwitterSettings.AccessTokenClaimType);
                var accessTokenSecretClaim = claims.FirstOrDefault(x => x.Type == TwitterSettings.AccessTokenSecretClaimType);

                if (accessTokenClaim != null && accessTokenSecretClaim != null)
                {
                    // Initialize the Twitter client
                    var service = new TwitterService(
                        TwitterSettings.ConsumerKey,
                        TwitterSettings.ConsumerSecret,
                        accessTokenClaim.Value,
                        accessTokenSecretClaim.Value
                    );

                    var profile = service.GetUserProfile(new GetUserProfileOptions());
                    // Try to download user image.
                    if (profile != null && !String.IsNullOrWhiteSpace(profile.ProfileImageUrlHttps))
                    {
                        string filename = Server.MapPath(string.Format("~/ProfileImages/{0}.jpeg", userId));
                        await DownloadProfileImage(new Uri(profile.ProfileImageUrlHttps), filename);
                    }
                }
            }
        }