Coder Social home page Coder Social logo

jaredhanson / passport-twitter Goto Github PK

View Code? Open in Web Editor NEW
466.0 15.0 127.0 126 KB

Twitter authentication strategy for Passport and Node.js.

Home Page: https://www.passportjs.org/packages/passport-twitter/?utm_source=github&utm_medium=referral&utm_campaign=passport-twitter&utm_content=about

License: MIT License

JavaScript 99.66% Makefile 0.34%
passport twitter oauth

passport-twitter's Introduction

passport-twitter

Passport strategy for authenticating with Twitter using OAuth 1.0a.

This module lets you authenticate using Twitter in your Node.js applications. By plugging into Passport, Twitter authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

Developed by Jared Hanson.

Advertisement
The Complete Node.js Developer Course
Learn Node. js by building real-world applications with Node, Express, MongoDB, Jest, and more!

Install

$ npm install passport-twitter

Usage

Create an Application

Before using passport-twitter, you must register an application with Twitter. If you have not already done so, a new application can be created at Twitter Application Management. Your application will be issued a consumer key (API Key) and consumer secret (API Secret), which need to be provided to the strategy. You will also need to configure a callback URL which matches the route in your application.

Configure Strategy

The Twitter authentication strategy authenticates users using a Twitter account and OAuth tokens. The consumer key and consumer secret obtained when creating an application are supplied as options when creating the strategy. The strategy also requires a verify callback, which receives the access token and corresponding secret as arguments, as well as profile which contains the authenticated user's Twitter profile. The verify callback must call cb providing a user to complete authentication.

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, cb) {
    User.findOrCreate({ twitterId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

Authenticate Requests

Use passport.authenticate(), specifying the 'twitter' strategy, to authenticate requests.

For example, as route middleware in an Express application:

app.get('/auth/twitter',
  passport.authenticate('twitter'));

app.get('/auth/twitter/callback', 
  passport.authenticate('twitter', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

Examples

Developers using the popular Express web framework can refer to an example as a starting point for their own web applications.

Authors

License

The MIT License

Copyright (c) 2011-2023 Jared Hanson

passport-twitter's People

Contributors

a0viedo avatar adaoraul avatar itsjw avatar jaredhanson avatar keith24 avatar n1c avatar peterwarbo avatar robertdimarco avatar rockingskier avatar stevebest avatar therealplato avatar tj avatar tobobo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

passport-twitter's Issues

does this Strategy require sessions?

According to the Passport docs you should be able to disable sessions when authenticating like so:

passport.authenticate('twitter', {
  callbackURL: '...',
  session: false
});

When I do so I still get the following error:

Error: OAuthStrategy requires session support. Did you forget app.use(express.session(...))?

Is this something I'm missing or does this require sessions?

passport-twitter not working with the newest version of express

I am not able to make work passport-twitter with the newest version of express. I am using the 4.12.2 and i always get this error:
Error: OAuthStrategy requires session support. Did you forget app.use(express.session(...))?

But i already added:

var app = express();
app.use(passport.initialize());
app.use(passport.session());

Do you have any example working with a new version of express?

Sample error: “InternalOAuthError: failed to obtain request token”

I get this when trying the sample.

This is my callback URL:

callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"

InternalOAuthError: failed to obtain request token
at /Users/frode/Dropbox/Nettsider/signin/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:155:36
at /Users/frode/Dropbox/Nettsider/signin/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:510:17
at passBackControl (/Users/frode/Dropbox/Nettsider/signin/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:366:13)
at IncomingMessage. (/Users/frode/Dropbox/Nettsider/signin/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:378:9)
at IncomingMessage.emit (events.js:88:20)
at HTTPParser.onMessageComplete (http.js:137:23)
at CleartextStream.ondata (http.js:1137:24)
at CleartextStream._push (tls.js:367:27)
at SecurePair.cycle (tls.js:688:20)
at EncryptedStream.write (tls.js:122:13)

How to use passport-twitter through Objective-C

Hi,

I am using Passport (facebook, Twitter, Google, and local) on my Node.js and it works perfectly from browsers.

I was wondering how to handle sign up/ sign stage through other devices where you don't want to involve the browser. I succeeded in local strategy where I first post username/password for my /login route and then get the api URL I want but no luck in Twitter and other social networks.

I couldn't find anything in documentation to see how to use this strategy (or others) via URL. Maybe I can get things I need from the device (lets say the native Twitter feature in social.framework and account.framework) and send it to my server to authenticate or authorize. Or maybe some other solutions like using other strategies.

Any help or solution would be much appreciate it :)

force_login doesn't work

in my project ,i need forelogin twitter,but this url( "/auth/twitter?force_login=true" ),the force_login doesn't work

sample failing with message 'oauth_token_secret' of undefined

I added Consumer key and Consumer Secret to the sample.

Then I logged in.

This was the browser url.

http://127.0.0.1:3000/auth/twitter/callback?oauth_token=ckjojfuTz2ZQBqRJNpiDniHP2VdpH0m2pXwGmgl85M&oauth_verifier=UpLb0TwmuRJwURuGwbuKoFjgKUh0oUoG3zkdgvKtU

TypeError: Cannot read property 'oauth_token_secret' of undefined
at Strategy. (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:119:71)
at Strategy.authenticate (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/passport-twitter/lib/passport-twitter/strategy.js:79:40)
at Passport.authenticate (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/passport/lib/passport/middleware/authenticate.js:120:14)
at callbacks (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/express/lib/router/index.js:272:11)
at param (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/express/lib/router/index.js:280:4)
at Object.handle (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/express/lib/router/index.js:45:10)
at Context.next (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/express/node_modules/connect/lib/http.js:203:15)
at Context. (/Users/pavelsmacbookpro/Projects/test.com/node_modules/passport-twitter/examples/signin/node_modules/passport/lib/passport/context/http/actions.js:64:8)

Error: Failed to find request token in session

Following is the error-

Error: Failed to find request token in session
at Strategy.OAuthStrategy.authenticate (/MYPROJECT/node_modules/passport-twitter/node_modules/passport-oauth1/lib/strategy.js:142:54)
at Strategy.authenticate (/MYPROJECT/node_modules/passport-twitter/lib/strategy.js:85:40)
at attempt (/MYPROJECT/node_modules/passport/lib/middleware/authenticate.js:337:16)
at Object.authenticate as handle
at next_layer (/MYPROJECT/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/MYPROJECT/node_modules/express/lib/router/route.js:107:5)
at /MYPROJECT/node_modules/express/lib/router/index.js:205:24
at Function.proto.process_params (/MYPROJECT/node_modules/express/lib/router/index.js:269:12)
at next (/MYPROJECT/node_modules/express/lib/router/index.js:199:19)
at next (/MYPROJECT/node_modules/express/lib/router/index.js:176:38)

This is the URL I followed for twitter(FYI- facebook signup is working correctly) http://scotch.io/tutorials/javascript/easy-node-authentication-twitter

My app.js file is - http://pastebin.com/Q9CN6Uvf
My passport.js file is - http://pastebin.com/BggGkzNw
My model is - http://pastebin.com/uN59T636

Let me know what I am doing wrong.

My development URL is like - http://192.XXX.XXX.XX:PORT_NUMBER

I checked settings in my twitter acc multiple times as well, still no luck :(

As a note I am using Express 4.

"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "1.2.x",
"connect-flash": "^0.1.1",
"cookie-parser": "1.1.x",
"express": "4.2.x",
"express-session": "1.2.x",
"forever": "^0.11.1",
"mongoose": "3.8.x",
"passport": "^0.2.0",
"passport-facebook": "^1.0.3",
"passport-local": "^1.0.0",
"passport-twitter": "^1.0.2"
}

can we catch error responses on the request token?

I see some errors like this on auth0 logs:

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <error>Desktop applications only support the oauth_callback value 'oob'</error>
  <request>/oauth/request_token</request>
</hash>

It will be nice to decode this and use that error message instead.

Best way to keep Profile Image current

How should we make sure the most recent profile image is displayed? Should we create a new TwitterStrategy() each time we want to display the profile image in an app (highly doubtful)? Should there only be one TwitterStrategy() throughout the app?

@Anywhere domains

if starting authenticating from a domain in the app @anywhere domain list (i.e. not the callback domain) the callback fails.
Not sure if a bug but the same works in passport-facebook

access level support?..

👋 really appreciate the lib - thanks!

i recently had need to upgrade my app's default access level. after some digging, i ended up just overriding the requestTokenURL strategy options.

e.g.

requestTokenURL: 'https://api.twitter.com/oauth/request_token?x_auth_access_type=write'

not sure if this is the best approach long(er)-term. perhaps you could accept the level directly as an option param? at the least, might be handy to call it out the above approach in the docs. happy to tackle either / other approach if it will be helpful :)

-matt

expired Token

after I send request to the twitter it starts to load on and on...
Redirecting you back to the application. This may take a few moments.
and in one moment displays:
If your browser doesn't redirect you please click here to continue
after I click I get:
500 Error: Invalid / expired Token at Strategy.parseErrorResponse (/srv/nodejs/node_modules/passport-twitter/lib/strategy.js:178:10)
is there some explanation for this? or someone had similar problem?

Module not working in clustered mode

The module does not seem to work in Cluster mode (It only works if i explicitly use something like connect-redis, otherwise, i am getting a "Failed to find request token in session" 500 error on return from twitter.

Best Regards,

Alex

Error: failed to find request token in session

Here is my error.
Some of the users experience this others not, or sometime they do, some times not, and that's quite frustrating since I generally loose 30/40 users per day :)

2012-06-18T19:40:01+00:00 app[web.1]: Error: failed to find request token in session 2012-06-18T19:40:01+00:00 app[web.1]: at Strategy.<anonymous> (/app/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:120:54) 2012-06-18T19:40:01+00:00 app[web.1]: at Strategy.authenticate (/app/node_modules/passport-twitter/lib/passport-twitter/strategy.js:82:40) 2012-06-18T19:40:01+00:00 app[web.1]: at callbacks (/app/node_modules/express/lib/router/index.js:272:11) 2012-06-18T19:40:01+00:00 app[web.1]: at Passport.authenticate (/app/node_modules/passport/lib/passport/middleware/authenticate.js:153:14) 2012-06-18T19:40:01+00:00 app[web.1]: at param (/app/node_modules/express/lib/router/index.js:246:11) 2012-06-18T19:40:01+00:00 app[web.1]: at pass (/app/node_modules/express/lib/router/index.js:253:5) 2012-06-18T19:40:01+00:00 app[web.1]: at Context.next (/app/node_modules/express/node_modules/connect/lib/http.js:204:15) 2012-06-18T19:40:01+00:00 app[web.1]: at Router._dispatch (/app/node_modules/express/lib/router/index.js:280:4) 2012-06-18T19:40:01+00:00 app[web.1]: at Object.handle (/app/node_modules/express/lib/router/index.js:45:10) 2012-06-18T19:40:01+00:00 app[web.1]: at Context.<anonymous> (/app/node_modules/passport/lib/passport/context/http/actions.js:64:8)

Here is part of my code

  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
//  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat', maxAge: new Date(Date.now() + 7200000), store: new RedisStore({client: store}) }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

[...]

passport.use(new TwitterStrategy({ consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, callbackURL: "http://www.commentaindiretta.it/auth/twitter/callback"},
function(token, tokenSecret, profile, done) {
    profile.token = token;
    profile.tokenSecret = tokenSecret;
    process.nextTick(function () {
        // To keep the example simple, the user's Facebook profile is returned to // represent the logged-in user.  In a typical application, you would want // to associate the Facebook account with a user record in your database, // and return that user instead.
        return done(null, profile);
    });
}));```

Any help or hint would be appreciated,
n

Error: Failed to parse user profile

I was trying to do a release, and it has turned this error.

Error: Failed to parse user profile
    at /home/node_modules/passport-twitter/lib/strategy.js:132:14
    at passBackControl (/home/node_modules/passport-twitter/node_modules/passport-oauth1/node_modules/oauth/lib/oauth.js:367:11)
    at IncomingMessage.<anonymous> (/home/node_modules/passport-twitter/node_modules/passport-oauth1/node_modules/oauth/lib/oauth.js:386:9)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

what happens is that I have already registered and logged on users, but when I need the command req.user, runs and always shows the same error.

In reviewing the lines 133 and 132, there is an undefined variable, ex. I would like to know so that it does and I can not run it?

https://github.com/jaredhanson/passport-twitter/blob/master/lib/strategy.js#L132
https://github.com/jaredhanson/passport-twitter/blob/master/lib/strategy.js#L133

This is a great library but how you handle subdomains?

I have an app where a use could login on: subX.domain.com
and another user could login on subY.domain.com

The fact that the callbackURL is setup initially and bound to the app, makes it impossible for passport to authenticate a user correctly. Ideally, the twitter strategy handler (your second function passed into TwitterStrategy) should be set by user.

I guess this is not easy change or might not even be possible with passport.

Damiano

Better handling for non-XML responses from Twitter

In certain failure conditions Twitter returns HTML (with the one-handed robot image) rather than an XML response for getOAuthAccessToken and/or getOAuthRequestToken. In this case passport-twitter will propagate an Error object with a message set to the HTML of the returned page, which is difficult to deal with and doesn't present well to users or in logs.

I would suggest that parseErrorResponse should return null in the case that body isn't well-formed XML and/or doesn't contain the expected elements so that '_createOAuthError' can return an Error with a more useful message. If the body is potentially useful, perhaps it could be added as a separate property of the Error object?

Thanks for considering,
Kevin

Route middleware functionality not working

So I'm running twitter-passport w/ Express 4.0, but the route middleware functionality advertised isn't working for me. The reason is that I'm using this module in conjunction with an iOS app and I want to send a JSON object to the server instead of a simple redirect. Is there are anything wrong with my syntax?

Here's sample code:

app.get('/auth/twitterX/callback', passport.authenticate('twitter'),function(req,res){
    console.log("Made it past passport authen");    
    res.json({"status":"success"});
});

Basically I never get the console.log message displayed.

Twitter-Passport Strategy does not hold user in session. Log-in is required everytime. Which is not the case when using the same code for Passport-Facebook and Google Authentication.

 var twitterUserSchema = new mongoose.Schema({
   provider: String, 
   id: String,
   username: String,
   name: String,
   displayName: String,
   email: String,
});

var twitterUser= mongoose.model('twitterUser', twitterUserSchema);
var twitterUserInstance = new twitterUser;

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "/auth/twitter/callback"
},

function(accessToken, refreshToken, profile, done) {                                    
                  process.nextTick(function () {
                    twitterUser.find({id: profile.id},
                    function(err, TIU) {                  
                    console.log(TIU.length);                
            }
          );
        });

   return done(null, profile);
}      

));

Passport-twitter fails when used with cookieSession and signed cookies

Hi all,

here is the configuration of my app:

var app = express();

app.configure(function(){
    app.use(express.compress());
    app.use(express.static(path.join(__dirname, 'public')));
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.set('port', process.env.PORT || 8000);
    app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser('keyboard cat'));
    app.use(express.cookieSession({ secret: 'keyboard cat', cookie: { maxAge: 1000*60*60*24*30, httpOnly: true } }));
    app.use(flash());
    app.use(passport.initialize());
    app.use(passport.session());

    app.use(function (req, res, next) {
        console.log(req.signedCookies['connect.sess']);
        next();
    });

    app.use(app.router);
});

When I get rid of the secret in cookieParser, everything works as expected but with the secret this is what happens:

GET /auth/twitter 302 696ms

{ 
  passport: {},
  'oauth:twitter':
   { oauth_token: 'LKRBq2FP02cZhESVQT7vPoKoRAXS6Mon8Lm83P0Q',
     oauth_token_secret: 'SehbNP1rruTadMySb0b4UFwNJtAv3SQXysEijNjc' 
   } 
}

Error: Failed to find request token in session
    at Strategy.OAuthStrategy.authenticate (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/passport-twitter/node_modules/passport-oauth1/lib/strategy.js:142:54)
    at Strategy.authenticate (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/passport-twitter/lib/strategy.js:85:40)
    at attempt (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/passport/lib/passport/middleware/authenticate.js:243:16)
    at Passport.authenticate (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/passport/lib/passport/middleware/authenticate.js:244:7)
    at callbacks (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/express/lib/router/index.js:161:37)
    at param (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/express/lib/router/index.js:135:11)
    at pass (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/express/lib/router/index.js:142:5)
    at Router._dispatch (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/express/lib/router/index.js:170:5)
    at Object.router (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/express/lib/router/index.js:33:10)
    at next (/home/ec2-user/Dropbox/Work/Web Dev/RunningHeroes/node_modules/express/node_modules/connect/lib/proto.js:199:15)

GET /auth/twitter/callback?oauth_token=LKRBq2FP02cZhESVQT7vPoKoRAXS6Mon8Lm83P0Q&oauth_verifier=Yg5mHTVBCKR6F0Y092aY3rtlRnLcZpIy1t9lz9TuWA 500 8ms

So the token is present apparently, since it gets logged, but passport-twitter can't read it, is it because the value is signed?

I've read that thread which is why I tried without the secret in cookieParser but the thing is I need to sign cookie later on in the app so I need to keep the secret...

I've also read this similar issue but it doesn't seem to apply here. Any ideas?

Twitter Auth not working - API Discontinued

It looks like Twitter has completely dropped v1 of their API. Passport-twitter is now not working, after making 0 changes on my site:

Express
500 failed to fetch user profile (status: 410 data: {"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]})

at /www/grasstweets/node_modules/passport-twitter/lib/passport-twitter/strategy.js:107:30
at passBackControl (/www/grasstweets/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:374:13)
at IncomingMessage. (/www/grasstweets/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:386:9)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:910:16
at process._tickCallback (node.js:415:13)

Error on running in heroku

I just updated and deployed to heroku to take advantage of the improved logging, but I now get this error:

2012-04-05T12:25:11+00:00 heroku[web.1]: Starting process with command node web.js
2012-04-05T12:25:11+00:00 app[web.1]:
2012-04-05T12:25:11+00:00 app[web.1]: node.js:134
2012-04-05T12:25:11+00:00 app[web.1]: throw e; // process.nextTick error, or 'error' event on first tick
2012-04-05T12:25:11+00:00 app[web.1]: ^
2012-04-05T12:25:11+00:00 app[web.1]: Error: Cannot find module './utils'
2012-04-05T12:25:11+00:00 app[web.1]: at Function._resolveFilename (module.js:320:11)
2012-04-05T12:25:11+00:00 app[web.1]: at Function._load (module.js:266:25)
2012-04-05T12:25:11+00:00 app[web.1]: at require (module.js:348:19)
2012-04-05T12:25:11+00:00 app[web.1]: at Object. (/app/node_modules/passport-twitter/node_modules/p
assport-oauth/lib/passport-oauth/strategies/oauth2.js:7:13)
2012-04-05T12:25:11+00:00 app[web.1]: at Module._compile (module.js:404:26)
2012-04-05T12:25:11+00:00 app[web.1]: at Object..js (module.js:410:10)
2012-04-05T12:25:11+00:00 app[web.1]: at Module.load (module.js:336:31)
2012-04-05T12:25:11+00:00 app[web.1]: at Function._load (module.js:297:12)
2012-04-05T12:25:11+00:00 app[web.1]: at require (module.js:348:19)
2012-04-05T12:25:11+00:00 app[web.1]: at Object. (/app/node_modules/passport-twitter/node_modules/p
assport-oauth/lib/passport-oauth/index.js:5:22)

normalize provider params

Hi!

This one uses consumerKey and consumerSecret while most others clientID and clientSecret. I wonder if this could made to take also clientID and clientSecret (with some assignments done internally)?

TIA,
--Vladimir

Add documentation for skipExtendedUserProfile option

I came across the skipExtendedUserProfile option in the code and it is great! It makes the transition from Twitter back to the website much snappier for my use case. Awesome! I didn't see it in the documentation (README.md or passportjs.org), which is a shame since I'm guessing users are unaware and I think it would be appreciated.

Cheers,
Kevin

Failed to validate oauth signature and token at Strategy.parseErrorResponse

Since #9 is closed, I'm not sure if anyone is looking for posts there. I tried all suggested solutions, still having issues. quadruple-checked consumer key, secret, callback url; my machine syncs to time.apple.com, so I doubt it's off compared to twitter...any ideas?

Error: Failed to validate oauth signature and token at Strategy.parseErrorResponse (/Users/matijaabicic/work/Development/LicensePlate/node_modules/passport-twitter/lib/strategy.js:178:10) at Strategy.OAuthStrategy._createOAuthError (/Users/matijaabicic/work/Development/LicensePlate/node_modules/passport-twitter/node_modules/passport-oauth1/lib/strategy.js:349:16) at /Users/matijaabicic/work/Development/LicensePlate/node_modules/passport-twitter/node_modules/passport-oauth1/lib/strategy.js:218:41 at /Users/matijaabicic/work/Development/LicensePlate/node_modules/passport-twitter/node_modules/passport-oauth1/node_modules/oauth/lib/oauth.js:543:17 at passBackControl (/Users/matijaabicic/work/Development/LicensePlate/node_modules/passport-twitter/node_modules/passport-oauth1/node_modules/oauth/lib/oauth.js:397:13) at IncomingMessage. (/Users/matijaabicic/work/Development/LicensePlate/node_modules/passport-twitter/node_modules/passport-oauth1/node_modules/oauth/lib/oauth.js:409:9) at IncomingMessage.EventEmitter.emit (events.js:117:20) at _stream_readable.js:920:16 at process._tickCallback (node.js:415:13)

Update to API v1.1

Twitter deprecated the v1.0 so from today we are unable to use this module to login with Twitter.
(Source: https://dev.twitter.com/blog/api-v1-is-retired)

Error:

status: 410 data: {"errors": [{"message": "The Twitter REST API v1 will soon stop functioning. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}

It would be nice to make this module compatible with the v1.1.

Twitter api changed to version 1.1

After logging into twitter I get the following error:

failed to fetch user profile (status: 410 data: {"errors": [{"message": "The Twitter REST API v1 will soon stop functioning. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]})
    at C:\Users\dtorres.G-OFFICE\Dropbox\Private\Sites\derby-user\node_modules\passport-twitter\lib\passport-twitter\strategy.js:107:30
    at passBackControl (C:\Users\dtorres.G-OFFICE\Dropbox\Private\Sites\derby-user\node_modules\passport-twitter\node_modules\passport-oauth\node_modules\oauth\lib\oauth.js:374:13)
    at IncomingMessage.<anonymous> (C:\Users\dtorres.G-OFFICE\Dropbox\Private\Sites\derby-user\node_modules\passport-twitter\node_modules\passport-oauth\node_modules\oauth\lib\oauth.js:386:9)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:910:16
    at process._tickCallback (node.js:415:13)

failed to obtain request token (Error: connect ETIMEDOUT)

I am following the example but unable to get any success..

This is how i am setting my strategy
passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: "http://127.0.0.1:8080/auth/twitter/callback"
},
function(token, tokenSecret, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {

        // To keep the example simple, the user's Twitter profile is returned to
        // represent the logged-in user.  In a typical application, you would want
        // to associate the Twitter account with a user record in your database,
        // and return that user instead.
        return done(null, profile);
    });
}

));

I have put the same callback url in my application setting on twitter
twitter app

i am getting this error
failed to obtain request token (Error: connect ETIMEDOUT)
at D:\Software Projects\botnik-server\node_modules\passport-twitter\node_modules\passport-oauth\lib\passport-oauth\strategies\oauth.js:184:36
at D:\Software Projects\botnik-server\node_modules\passport-twitter\node_modules\passport-oauth\node_modules\oauth\lib\oauth.js:512:17
at ClientRequest. (D:\Software Projects\botnik-server\node_modules\passport-twitter\node_modules\passport-oauth\node_modules\oauth\lib\oauth.js:391:7)
at ClientRequest.emit (events.js:67:17)
at CleartextStream.socketErrorListener (http.js:1188:9)
at CleartextStream.emit (events.js:67:17)
at Socket.onerror (tls.js:1146:17)
at Socket.emit (events.js:88:20)
at Array.0 (net.js:301:14)
at EventEmitter._tickCallback (node.js:190:38)

TypeError: Cannot read property 'oauth_token_secret' of undefined

Hitting this error with Twitter. The problem is here:

at Strategy. (/Users/me/bits/stash/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:119:71)

Line 119:
this._oauth.getOAuthAccessToken(oauthToken, req.session[self._key]["oauth_token_secret"], oauthVerifier, function(err, token, tokenSecret, params) {

req.session[self._key] is null/undefined. Problem is down in OAuth strategy.

Anyone else running into this scenario?

REST API v1 notice

Hi,

I started getting the following error message just now...anybody has any ideas?
this happens on .../auth/twitter/callback?oauth_token=blah&oauth_verifier=blah

failed to fetch user profile (status: 410 data: {"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]})
at D:\Documents..\node_modules\passport-twitter\lib\passport-twitter\strategy.js:107:30
at passBackControl (D:\Documents..\node_modules\passport-twitter\node_modules\passport-oauth\node_modules\oauth\lib\oauth.js:374:13)
at IncomingMessage. (D:\Documents..\node_modules\passport-twitter\node_modules\passport-oauth\node_modules\oauth\lib\oauth.js:386:9)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:910:16
at process._tickCallback (node.js:415:13)

Thanks,
Jatin

The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.

Looks like Twitter abandoned support for v1 API. Any change we could get an update?

    failed to fetch user profile (status: 410 data: {"errors": [{"message": "The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]})
    at Strategy.userProfile.profile.provider (/var/surveyplanet.com/node_modules/passport-twitter/lib/passport-twitter/strategy.js:107:30)
    at passBackControl (/var/surveyplanet.com/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:374:13)
    at IncomingMessage.exports.OAuth._performSecureRequest.request.on.callbackCalled (/var/surveyplanet.com/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.
    at IncomingMessage.EventEmitter.emit (events.js:126:20)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at CleartextStream.socketOnData [as ondata] (http.js:1367:20)
    at CleartextStream.CryptoStream._push (tls.js:526:27)
    at SecurePair.cycle (tls.js:880:20)
    at EncryptedStream.CryptoStream.write (tls.js:267:13)

callback

in this repo - https://github.com/mjhea0/passport-twitter-profile

i have the callback set as http://localhost:1337/auth/twitter/callback; however, in my twitter settings it's set as http://127.0.0.1:1337/auth/twitter/callback. this works. when i try to set the callback as http://127.0.0.1:1337/auth/twitter/callback, it doesn't work. i don't understand this. i thought the callback had to match exactly what's in twitter.

passport.use(new TwitterStrategy({
  consumerKey: config.twitter.consumerKey,
  consumerSecret: config.twitter.consumerSecret,
  callbackURL: "http://localhost:1337/auth/twitter/callback"
  // callbackURL: "http://127.0.0.1:1337/auth/twitter/callback"  
}, 
function(token, tokenSecret, profile, done) {
    profile.twitter_token = token;
    profile.twitter_token_secret = tokenSecret;
    process.nextTick(function () {
      return done(null, profile);
    });
  }
));

Issue with example - "Failed to validate oauth signature and token"

I've been getting some odd behavior with twitter-passport so I decided to try the example, however when I run it and click the "Sign in with twitter" link I get the following error (regardless of whether I am already logged into twitter or not):

failed to obtain request token (status: 401 data: Failed to validate oauth signature and token)
    at /home/colin/Desktop/jaredhanson-passport-twitter-086ca27/examples/signin/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:163:36
    at /home/colin/Desktop/jaredhanson-passport-twitter-086ca27/examples/signin/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:510:17
    at passBackControl (/home/colin/Desktop/jaredhanson-passport-twitter-086ca27/examples/signin/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:366:13)
    at IncomingMessage.<anonymous> (/home/colin/Desktop/jaredhanson-passport-twitter-086ca27/examples/signin/node_modules/passport-twitter/node_modules/passport-oauth/node_modules/oauth/lib/oauth.js:378:9)
    at IncomingMessage.emit (events.js:88:20)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at CleartextStream.ondata (http.js:1124:24)
    at CleartextStream._push (tls.js:363:27)
    at SecurePair.cycle (tls.js:685:20)
    at EncryptedStream.write (tls.js:122:13)

oauth2

It looks like twitter supports oauth2 (I might be wrong).

My applications use jwt, and allow connecting via facebook, google plus and github, but not twitter. The reason for this is that passport-twitter uses oath 1.0 which requires a session.

Is it possible to update to 2.0?

Custom callback: prompt for email

Twitter doesn't return an email address, so how would you prompt the user to enter an email address before their account is created?

Redirects to twitter Sign In (authorize) page every time

I've just created a sample app based closely on the example in the repo and it always asks the user to Sign In via twitter (as if authorizing the app for the first time).

Meaning that GET /account redirects to GET /authn/twitter which does passport-twitter magic and calls back to GET /oauth/twitter/callback which then redirects back to GET /account. This happens every time, regardless of already having authorized the app and already being signed into twitter.

Any thoughts on why this would happen?

[iOS Safari] Failed to find request token in session at Strategy.OAuthStrategy.authenticate

A week ago, everything was working fine. I have passport-twitter, passport-facebook, and passport-reddit all working from OSX and iOS using Chrome and Safari.

This week, passport-twitter (and passport-reddit) authentication no longer works from iOS Safari. (passport-facebook is still fine from all platforms and browsers but I suspect it's just different authentication protocol.)

Authentication still works if it's on iOS Chrome. It also works on OS X Safari. So my guess is something (maybe cookie or session management policy) changed in iOS Safari.

Additional info. The failure is consistent and is on my production server (so it's not related to localhost!=127.0.0.1 issue in other threads).

Please let me know what other info you need.

Custom redirects in passport or different success redirect URLs

I am trying to set up a basic authentication for my first public facing node app. I have two passport strategies: 1) for Facebook and 2) For Twitter. I do not plan to include an email/password system at least for now till I understand the security implications. I have been able to get them working in an out of the box way and tie in Mongoose for creating new users.

I now want to work on deduping social account users. So whenever a new user comes in via twitter auth I want to redirect them to a page that collects email. I am saving the token and profile object returned as session variables and would reuse them on that page when submitting the form as hidden fields.

However I cannot understand how to implement this aspect using Passport. Here is the code I have so far with comments on what I am trying to do with each part. Essentially I am checking if the twitter user is an old user, if not I am setting session variables that I will reuse on the /addemail page, initializing the user object (so that Serialize, Deserialize function has something to act (not sure I understand what Serializing/Deserializing actually does). Now if the user is a new one, the session variable NewTwitterUser is true and I check it in the auth/callback url to redirect the user to appropriate page. This however does not work.

//basic modules and setup
var express = require('express')
    , passport = require('passport')
    , mongoose = require('mongoose')
    , http = require('http')
    , util = require('util')
    , TwitterStrategy = require('passport-twitter').Strategy
    , FacebookStrategy = require('passport-facebook').Strategy
    , path = require('path');

var app = express();


//Mongodb setup
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
  provider: String,
  uid: String,
  fb_uid: String,
  twitter_uid: String,
  name: String,
  first_name: String,
  gender: String,
  fb_username: String,
  twitter_username: String,
  profile_pic: String,
  email: String,
  location: String,
  birthday: String,
  created: {type: Date, default: Date.now}
});


var User = mongoose.model('User', UserSchema);
mongoose.connect('MongoHQ db connection here')'


//User Authentication - Twitter
passport.use(new TwitterStrategy({
    consumerKey: 'KEY',
    consumerSecret : 'SECRET',
    callbackURL: "CALLBACKURL",
    passReqToCallback: true
},
    function(req, token, tokenSecret, profile, done){
        User.findOne({twitter_uid: profile.id}, function(err, user){
            if (err) {
            console.log('this is an error 1' + err);
            return done(err);}
            if(user){
                console.log('this user' + user);
                done(null, user);
            } else {
                console.log('this is a new user');
                req.session.token = token;
                req.session.tokenSecret = tokenSecret;
                req.session.profile = profile;
                req.session.newtwitteruser = true;
                var user = new User();
                user.uid = profile.id;
                done(null, user);

                /* This part is commented and is the default code I had if I needed to simply create a Twitter User right here.
                var user = new User();
                user.provider = profile.provider;
                user.uid = profile.id;
                user.twitter_uid = profile.id;
                user.name = profile.displayName;
                user.first_name = profile.displayName[0];
                user.twitter_username = profile._json.screen_name;
                user.profile_pic = profile._json.profile_image_url;
                user.location = profile._json.location;
                user.save(function(err){
                    if(err) {throw err;}
                    else {done(null, user);}
                });*/
            }
        }); 
    }   
));


//User Authentication - Facebook
passport.use(new FacebookStrategy({
    clientID: 'ID',
    clientSecret: 'SECRET',
    callbackURL: "URL"
},
    function(accessToken, refreshToken, profile, done){
        User.findOne({fb_uid: profile.id}, function(err, user){
            if (err) {return done(err);}
            if(user){
                done(null, user);
            } else {
                var user = new User();
                user.provider = profile.provider;
                user.uid = profile.id;
                user.fb_uid = profile.id;
                user.name = profile.displayName;
                user.first_name = profile._json.first_name;
                user.gender = profile._json.gender;
                user.fb_username = profile._json.username;
                user.profile_pic = 'https://graph.facebook.com/' + profile.id + '/picture';
                user.email = profile._json.email;
                user.location = profile._json.location.name;
                user.birthday = profile._json.birthday;
                user.save(function(err){
                    if(err) {throw err;}
                    else {done(null, user);}
                });
            }
        })  
    }   
));


passport.serializeUser(function(user, done) {
  done(null, user.uid);
});

passport.deserializeUser(function(uid, done) {
  User.findOne({uid: uid}, function (err, user) {
    done(err, user);
  });
});  


//app configurations
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser("freecookie"));
  app.use(express.session({secret:"freecookie"}));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.errorHandler());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
});


//Basic Routing
app.get('/', function(req, res){
    res.render('home', {title: 'App Title', user: req.user});
});


app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('/auth/twitter/callback', 
    passport.authenticate('twitter', {failureRedirect: '/login' }), 
    function(req, res) {
        if (req.session.newtwitteruser){
        res.redirect('/addemail');}
        else {res.redirect('/');}
    });

app.get('/addemail', function(req, res){
    if (req.session.newtwitteruser){
    res.render('email', {title: 'Add your Email'});}
    else {res.redirect('/');}
});


app.get('/auth/facebook', passport.authenticate('facebook', {scope: ['email', 'user_location', 'user_birthday'] }));

app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' }));  


app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});



//create the server
var server = http.createServer(app);
server.listen(app.get('port'));


//Checks if a request is authenticated
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

Failed to find request token in session

Hi, few days ago we started to receive error messages from our application, saying that some of our users encounter errors with Twitter OAuth authorization:

Error: Failed to find request token in session
    at Strategy.OAuthStrategy.authenticate 

But the app worked fine for past 2 month without any issues.

So, we started to investigate the issue and for that we made a new small clean node.js application (https://github.com/rnikitin/twitter-oauth-test) following step by step the passport.js instructions.
And if will you go to localhost:3000/auth/twitter after callback you will see this error:

Error: Failed to find request token in session
    at Strategy.OAuthStrategy.authenticate (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/passport-twitter/node_modules/passport-oauth1/lib/strategy.js:142:54)
    at Strategy.authenticate (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/passport-twitter/lib/strategy.js:85:40)
    at attempt (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/passport/lib/middleware/authenticate.js:337:16)
    at Object.authenticate [as handle] (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/passport/lib/middleware/authenticate.js:338:7)
    at next_layer (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/express/lib/router/route.js:103:13)
    at Route.dispatch (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/express/lib/router/route.js:107:5)
    at c (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/express/lib/router/index.js:195:24)
    at Function.proto.process_params (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/express/lib/router/index.js:251:12)
    at next (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/express/lib/router/index.js:189:19)
    at next (/Users/rnikitin/dev/rnikitin/twitter-oauth-test/node_modules/express/lib/router/index.js:166:38)

I also deployed this test app to a hosting, so you can go there: http://twitter-oauth-test.azurewebsites.net/auth/twitter/

Unfortunately the hosting hides all error messages from the remote user, but you will see exact same error message.

We spend whole day playing around but we were unable to figure it out. We tried everything - changing callback urls, domains, digging into passport-twitter module. We only found, that session comes back, but the value in session is undefined with this key.

So, does anybody has similar issues last few days? Do you have any ideas how to fix this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.