Showing posts with label api. Show all posts
Showing posts with label api. Show all posts

Tuesday, August 19, 2014

How to use OAuth with MEANJS

Nodejs logo
Hello, this is a short tutorial on how to use OAuth with meanjs.  It can be followed using another framework, but there are some mean-specific tips in here.  You probably do need node, though.







  • To use oauth with meanjs, you should find a library that has already implemented the handshaking for you (googleapis and Twit)
  • A note about OAuth 1 vs 2:
    • OAuth support is fragmented
    • Lots of node libraries support both
    • Not all services support 1 or 2
  • Note: if you plan on using user-based authentication along with application authentication, it is much easier to use the existing passport integration that meanjs already has in place
    • This makes obtaining session tokens much easier
  • Most often, these libraries will provide easy-to-use interfaces (APIs) where keys are passed as a config object
    • demoTwit.png
    • All you need to do is put in your keys where they are needed
  • To get access tokens, most of the time you need to create a new app
  • These instructions are pretty straightforward usually
  • The callback url can be found in config/env/development.js under the object whose service name you are using
  • Note: if you use a non-standard port on your app, you must specify that port in the callback url (127.0.0.1:3000/callback/)
  • A note on twitter’s api app creator:
    • For some reason, twitter doesn’t like localhost to be in the callback url, so you need to specify localhost using 127.0.0.1 eg
    • 127.0.0.1:3000/auth/twitter/callback
  • This will give you one or two application-specific tokens or secrets
    • These application-specific keys are used to authenticate your app
    • If you need per-user authentication as well, read on
  • To fill in the per-user authentication tokens, you need to interface with passport and the existing meanjs framework for these things
    • These session keys can be obtained from the user object after authenticating eg
var providerData = req.user.providerData || req.user._doc.additionalProvidersData.twitter;

   var T = new Twit({
       consumer_key: config.twitter.clientID,
       consumer_secret: config.twitter.clientSecret,
       access_token: providerData.token,
       access_token_secret: providerData.tokenSecret
   });

  • The branch googleApiDemo of my fork of extra-mean has a demo of something like this, feel free to use it as an example
  • Any questions?  Leave a comment or email me at macsj200@gmail.com