Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node WPAPI OAuth examples
var WPAPI = require( 'wpapi' );
var wp = new WPAPI({
endpoint: endpointUrl,
oauth: {
clientId: clientId,
clientSecret: clientSecret,
callback: callbackUrl // optional: (defaults to oob)
}
});
wp.getOAuthRequestUrl(function(url) {
// WPAPI does initial request token fetch, then constructs URL for authorizing the user
// How to process this URL is left up to the developer/implementation
var verifier = getVerifierFromUrl(url);
return verifier; // Accept either a string or a promise. Once resolved, wpapi will internally set the access tokens
}).then(function() {
// At this point, we have an access token and can start calling API end points
wp.users().me().then(function() { ... });
});
// OAuth configured as seperate library/object
var WPAPI = require( 'wpapi' );
// OAuth implementation is instead handled by a third-party library
var wpapiOAuth = require( 'wpapi-oauth' );
var wp = new WPAPI({
endpoint: endpointUrl
});
// authHandler expects object with "auth" function only. It will call this internally from _auth(), providing the ability to get method/url/qs/data, and set headers
// This allows development/injection of implementation-specific auth handlers, eg wpapi-oauth-express, wpapi-oauth-opn
wp.authHandler(new wpapiOAuth( clientId, clientSecret, callbackUrl )); // callback optional: (defaults to oob)
// When a call to a protected resource is requested, authhandler will be called and will block execution (using promises)
// until verification/request tokens are retrieved at which point the API call will resume as normal.
wp.users().me().then(function() { ... });
// Variation of Option2 (OAuth configured as seperate library/object)
var WPAPI = require( 'wpapi' );
var wpapiOAuth = require( 'wpapi-oauth' );
var wp = new WPAPI({
endpoint: endpointUrl
});
// authHandler expects object with "auth" and "authConfig" functions.
// It will call this internally from _auth(), providing the ability to get method/url/qs/data, and set headers
wp.authHandler( wpapiOAuth );
// Use existing auth functions but pass in OAuth-specific data. The object will be passed to the authHandler as well so it can store
// OAuth settings internall.
// Benefit of this approach is auth can be configured per-request (doesn't make a lot of sense for OAuth, but will be consistent)
wp.auth({clientId:clientId, clientSecret:clientSecret, callbackUrl:callbackUrl });
wp.users().me().then(function() { ... });// Variation of option2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment