npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wordpress-rest-api-oauth-2

v0.1.1

Published

WordPrest REST API OAuth 2 Client

Downloads

7

Readme

WordPress REST API OAuth 2 Client

JavaScript OAuth 2 Client for the WordPress REST API v2.

Based on https://github.com/WP-API/wordpress-rest-api-oauth-1

Install

npm install --save wordpress-rest-api-oauth-2

Configuration

Without Authentication

import api from 'wordpress-rest-api-oauth-2'

const demoApi = new api({
	url: 'https://demo.wp-api.org/'
})

Using OAuth 2 Directly

To communication and authenticate using OAuth 2 with your WordPress site directly:

import api from 'wordpress-rest-api-oauth-2'

const demoApi = new api({
	url: 'https://demo.wp-api.org/',
	credentials: {
		client: {
			id: 'xxxxxx',
			secret: 'xxxxxxxxxxxxxxxxxxx'
		}
	}
})

Using the WordPress Authentication Broker

WARNING: NOT YET SUPPORTED

To establish a connection to a WordPress site that accepts the WordPress REST API Broker:

import api from 'wordpress-rest-api-oauth-2'

const demoApi = new api({
	url: 'https://demo.wp-api.org/',
	brokerCredentials: {
		client: {
			id: 'xxxxxx',
			secret: 'xxxxxxxxxxxxxxxxxxx'
		}
	}
})

// Get OAuth client tokens for the specified site. This is not needed if using `authorize()`.
demoApi.getClientCredentials().then( token => {
	console.log( token )
})

Usage

Authorize / OAuth Flow

There is two ways to get authentication tokens, one "high level" function, or you can implement your own flow using the underlying function.

##### The Quick Way

demoApi.authorize().then( function() {
	console.log( 'All API requests are now authenticated.' )
})

// Note: the above will cause a redirect / resume of the app in the event that the user needs to authorize.
Control your own flow
// Get client tokens from the broker (optional)
demoApi.getClientCredentials().then( ... )

// Optionally create state to avoid CSRF and store
const state = createRandomState()
localStorage.setItem( 'oauthState', state )

// Send user to authorisation page...
window.location = demoApi.getRedirectURL( state )

// After return, exchange code for access token (after checking state)
demo.getAccessToken( code )
	.then( token => {
		// save the token to localStorage etc.
	})

Make API Requests

The recommended way to make requests is to use the API.fetch() method just as you would use the fetch() function. This method does a few things for you:

  • Resolves URLs relative to the API URL.
  • Automatically adds the Authorization header

Use it the same way you'd use fetch()

demoApi.fetch( 'wp/v2/posts' )
	.then( resp => resp.json() )
	.then( data => console.log( data ) )

The library can also parse the response for you and automatically throw errors:

import api, { parseResponse } from 'wordpress-rest-api-oauth-2';

// ...

demoApi.fetch( '/wp/v2/posts' )
	.then( parseResponse )
	.then( data => console.log( data ) )
	.catch( err => console.warn( err ) )

(If you need to access the underlying HTTP response data, use data.getResponse() in your .then callback.)

You can also use the high-level helpers:

demoApi.get( '/wp/v2/posts', { per_page: 5 } ).then( posts => {
	console.log( posts )
})

demoApi.post( '/wp/v2/posts', { title: 'Test new post' } } ).then( post => {
	console.log( post )
})

demoApi.del( '/wp/v2/posts/1' ).then( post => {
	console.log( 'Deleted post.' )
})

Loading and Saving Credentials

With OAuth in the browser, you don't typically want to run through the authorization flow on every page load, so you can export and import the credentials if you wish:

// init API with credentials:
new api({
	url: siteURL,
	credentials: JSON.parse( localStorage.getItem( 'authCredentials' ) )
})

// save the credentials
localStorage.setItem( 'authCredentials', JSON.stringify( demoApi.config.credentials ) )

You can also have the library store and retrieve the credentials:

demoApi.restoreCredentials().get( '/wp/v2/users/me' )

demoApi.saveCredentials() // Save the credentials to localStorage

To implement restoring of credentials and auth in one go:

demoApi.restoreCredentials().authorize().then( function() {
	demoApi.saveCredentials()
})