Problems with OAuth on node.js

前端 未结 3 1545
别跟我提以往
别跟我提以往 2021-01-30 14:33

I am trying to get OAuth to work on node.js. I found this in the documentation of node-oauth:

var OAuth= require(\'oauth\').OAuth;
var oa = new OAuth(requestUrl,         


        
3条回答
  •  不思量自难忘°
    2021-01-30 15:30

    I'm not sure what OAuth service you are trying to connect to so I'll just use twitter as an example. After you create your OAuth object you need to first request an oauth token. When you get that token, then you need to redirect to, for twitter, their authenticate page which either prompts them to login, then asks if it's ok for the app to login.

    oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){
      if (error) new Error(error.data)
      else {
        req.session.oauth.token = oauth_token
        req.session.oauth.token_secret = oauth_token_secret
        res.redirect('https://twitter.com/oauth/authenticate?oauth_token='+oauth_token)
       }
    });
    

    When you first created the OAuth object, you set a responseURL, or the callback url. It can be anything, for my app its just /oauth/callback. In that callback you receive the oauth verifier token. You then use both the oauth request token and oauth verifier token to request the access tokens. When you receive the access tokens you will also receive anything else they pass, like their username.

    app.get('/oauth/callback', function(req, res, next){
      if (req.session.oauth) {
        req.session.oauth.verifier = req.query.oauth_verifier
        var oauth = req.session.oauth
    
        oa.getOAuthAccessToken(oauth.token,oauth.token_secret,oauth.verifier, 
          function(error, oauth_access_token, oauth_access_token_secret, results){
            if (error) new Error(error)
            console.log(results.screen_name)
        }
      );
    } else
      next(new Error('No OAuth information stored in the session. How did you get here?'))
    });
    

    Hope this helps! I had the same problems when I started on this.

提交回复
热议问题