iOS & node.js: how to verify passed access token?

Viewed 13535

I have an iOS which uses OAuth and OAuth2 providers (Facebook, google, twitter, etc) to validate a user and provide access tokens. Apart from minimal data such as name and email address, the app doesn't uses these services for anything except authentication.

The app then sends the access token to a server to indicate that the user is authenticated.

The server is written in Node.js and before doing anything it needs to validate the supplied access token against the correct OAuth* service.

I've been looking around, but so far all the node.js authentication modules I've found appear to be for logging in and authenticating through web pages supplied by the server.

Does anyone know any node.js modules that can do simple validation of a supplied access token?

4 Answers

For google in production, install google-auth-library (npm install google-auth-library --save) and use the following:

const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(GOOGLE_CLIENT_ID); // Replace by your client ID

async function verifyGoogleToken(token) {
  const ticket = await client.verifyIdToken({
    idToken: token,
    audience: GOOGLE_CLIENT_ID  // Replace by your client ID 
  });
  const payload = ticket.getPayload();
  return payload;
}

router.post("/auth/google", (req, res, next) => {
  verifyGoogleToken(req.body.idToken).then(user => {
    console.log(user); // Token is valid, do whatever you want with the user 
  })
  .catch(console.error); // Token invalid
});

More info on Authenticate google token with a backend server, examples for node.js, java, python and php can be found.

For Facebook, do an https request like:

const https = require('https');

router.post("/auth/facebook", (req, res, next) => {

  const options = {
    hostname: 'graph.facebook.com',
    port: 443,
    path: '/me?access_token=' + req.body.authToken,
    method: 'GET'
  }

  const request = https.get(options, response => {
    response.on('data', function (user) {
      user = JSON.parse(user.toString());
      console.log(user);
    });
  })

  request.on('error', (message) => {
    console.error(message);
  });

  request.end();
})
Related