Add authorization header to Snapchat login callback using passport js strategy

Viewed 306

I'm trying to integrate login using Snapchat to my application. In order to do that I need to add an authorization bearer to the callback request to my application so I can verify the client. According to Snapchat guide I need to use _qs or Axios to create the request:

// ******************** URL Builder Helper ***********************

var _qs = require("qs"); // Will need to 'npm install qs'

var getAuthCodeRedirectURL = function getAuthCodeRedirectURL(
  clientId,
  redirectUri,
  scopeList,
  state
) {
  var SNAP_ACCOUNTS_LOGIN_URL =
    "https://accounts.snapchat.com/accounts/oauth2/auth";
  var scope = scopeList.join(" ");
  var loginQS = {
    client_id: clientId,
    redirect_uri: redirectUri,
    response_type: "code",
    scope: scope,
    state: state,
  };

  var stringifyLoginQS = _qs.stringify(loginQS);
  return SNAP_ACCOUNTS_LOGIN_URL + "?" + stringifyLoginQS;
};

However I'm not sure how I can include the link in the passport.js strategy.

Can you clarify on how it works?

1 Answers

To pass the Authorization header, you have to set up the headers in the request library:

// Set headers
const headers = {
    Authorization: "Basic " + authorizationHeaderBase64,
};

// Configure access token POST request
const options = {
    url: SNAPCHAT_AUTH_ENDPOINT,
    method: "POST",
    headers: headers,
    form: {...},
};

request(options)

However, if you use the Passport authentication, just using the keys and setting up the config like in the docs should do the trick:

passport.use(new SnapchatStrategy({
    clientID: snapchat_APP_ID,
    clientSecret: snapchat_APP_SECRET,
    callbackURL: "http://localhost:3000/auth/snapchat/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ snapchatId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

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

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