single-head-img

Ionic framework through WordPress API – Part II (Authentication)

May 9, 2017

Hello again and welcome back to my first tutorial about Ionic framework and WordPress REST API. This is the second post of this serial so far. I will write a lot about authorization on WP side and how to use it with Ionic framework, too.

WordPress REST API Authentication Methods

First of all, The WordPress REST API Handbook describe few methods about Authentication for an application to use WP REST API. Most noteworthy, cookie authentication is the standard authentication method included in WordPress. This type of authentication is for developers of themes and plugins, so once logged-in user get cookie and after that user can do anything with REST API. There are more methods for authentication, e.g. Application Passwords, JSON Web Tokens (JWT), Basic authentication plugin, OAuth 1.0a Server.

Creator of WP Basic Authentication plugins, Ryan McCue wrote: “This plugin requires sending your username and password with every request, and should only be used for development and testing. We strongly recommend using the OAuth 1.0a authentication handler for production.“. Basic authentication is not good solution for me, because I’m only one developer. So I just wanted to secure my WP REST API calls and also to get rights to change/delete some posts… I choose to work with OAuth 1.0a method.

OAuth 1.0a Server for WP REST API

OAuth (Open Authorization) is an open standard for token-based authentication on the Internet. This standard itself provides no ability to exchange a username and password for a user token. That means one client app – one token. There are OAuth1.0 and 2.0. Why to use OAuth 1.0a and not 2.0? OAuth v1 has complicated signature system which relies on shared secret. However, OAuth v2 relies on SSL/TLS for message authenticity. This means that OAuth 2.0 requires HTTPS. To enable authentication for all sites, not just HTTPS, I will use Server 1.0a.

How to use “OAuth 1.0a Server” plugin at all? Well, I just added that plugin through WordPress admin dashboard to my site. Furthermore, on “Users” menu item, there will appear “Application” sub-menu item. Therefore, by clicking there, I’ve got empty screen with button “Add New” next to title “Registered Applications”. This button will create new Consumer (Client) key and secret to use them in applications as a result. It seems like very easy to add new consumer name, description and callback URL. To check it, I’ve started POSTMAN extension on google chrome, set GET method, paste wp-json link of my site and as a result, I’ve got:

Authentication check

OAuth 1.0 Server – plugin check

 

Oauth 1.0a – POSTMAN perspective

As you can see on image above, there are three URLs I’ve got OAuth plugin offers. First one, request, send one request with consumer key and secret to my server to get needed tokens to authorize. Authorize URL needs to get key, secret and token (temporary) and after that we will get access to WP REST API for our application. To test all this things, I’ve used great POSTMAN extension, again.

First thing to do is to set method to POST and paste my request URL (//milos-ristic.com/oauth1/request). After sending this empty request, response from POSTMAN return “No OAuth parameters supplied.”. We should add parameters to our request and those parameters are: consumer key and secret. At POSTMAN, I choose Authorization “OAuth 1.0” and I’ve got empty fields for key and secret and more. I copied/pasted key and secret I’ve got from my plugin, set Signature Method on HMAC-SHA1 (recommended), checked “Add params to header”. By clicking on “Update Request”, POSTMAN will update fields like Nonce, Timestamp, etc. By sending this to my server, I’ve got response with OAuth token, secret and callback. I will use this info further to authorize myself on my site.

POSTMAN request

POSTMAN request token

 

I used this token and place it into “Token” field in POSTMAN. Also, I changed URL to authorize myself (//milos-ristic.com/oauth1/authorize). By sending POST request to authorize myself, I’ve got HTML. Because of that reason, I put URL with token in browser and get page to authorize myself.

“Authorize” step began with those tokens I’ve got. To authorize myself, I get oauth_token and oauth_token_secret (those tokens are temporary created) and add them to authorize URL and I’ve got URL //milos-ristic.com/oauth1/authorize?oauth_token=XXXXXXXXXXXXX&oauth_token_secret=XXXXXXXXXXXXXXXXXXXXXXX&oauth_callback_confirmed=true. I opened Google Chrome, went to this address and got WP window to authorize myself on “test” app.

Authorize OAuth step

 

I was logged in and that’s why this window appeared immediately. If you are not logged in, WP will ask you to do that and then to authorize yourself. By clicking “Authorize”, I’ve got verification token.

Now, I went to POSTMAN again to finally get access for my app. I’ve got consumer key, consumer secret, temporary token and temporary token secret and verification token. To use verification token, I will add it to my access URL (//milos-ristic.com/oauth1/access) and full URL now is //milos-ristic.com/oauth1/access?oauth_verifier=XXXXXXXXXXXXXX. Also, you should put temporary tokens into POSTMAN empty fields and send request.

WOOHOO… There’re finally oauth_token and oauth_token_secret for my app.

Access with OAuth 1.0a

 

Test Authorization

Test of authorization will be by sending DELETE method to my “Hello World” post with id 1 (//milos-ristic.com/wp-json/wp/v2/posts/1). Now, token and token secret fields in POSTMAN are tokens I’ve got in the final step, after access. By sending this request from POSTMAN, we’ve got message that I send post with id 1 to trash. SUCCESSFUL!

OAuth 1.0a in action with POSTMAN

 

Ionic Framework Implementation

The easiest way to authorize my application was to use node package (npm) called wordpress-rest-api-oauth-1. It’s fresh package created by Joe Hoyle and Ryan McCue (mentioned before as creator of OAuth 1.0 Server plugin). I made some changes to this plugin to work for me and here you can download that file. This package is using qs package to stringify needed tokens and great OAuth-1.0a package for authorization.

To test this app on chrome, web security must be disabled. It can be done on chrome with flag --disable-web-security. Firstly, we need to copy/paste chrome shortcut and rename second one to “Google Chrome (x-domain)”. After that, right click on that icon -> Properties. Into target field this line should be added: --disable-web-security --user-agent="Android" --user-data-dir="C:/temp-chrome-eng". Click “Apply”, then “OK”, and we will get chrome with message: “You are using an unsupported command-line flag: –disable-web-security. Stability and security will suffer.“. It’s important to know it’s just for testing, don’t use this chrome for internet browsing.

Chrome without security

 

I’ve created very simple app to DELETE (move to trash) post with id entered at input field. After first click on button “DELETE POST”, app will request us to authorize like on steps described above. After we authorize our app and save credentials, we can use this button without additional authorizations. I will try to DELETE “Hello World” post with id 1. If everything goes well, there will be message in console which will say: ““Hello World!” post is moved to trash.“.

DELETE post in action

 

Files home.html and home.ts for this example are:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="home">
  <ion-input placeholder="Enter POST ID"  [(ngModel)]="postid"></ion-input>
  <button ion-button (click)="requestMe()">DELETE POST</button>
</ion-content>
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

import api from 'wordpress-rest-api-oauth-1';

@Component({
  templateUrl: 'home.html'
})
export class HomePage {
    postid : any;

    constructor( private http: Http ) {}

	requestMe() {
		const demoApi = new api({
		    url: '//milos-ristic.com/',
		    credentials: {
		        client: {
		            key: 'XXXXXXXXXXXXX',
		            secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
		        }
		    },
		    callbackURL: 'http://localhost:8100/'
		});

		var pid = this.postid;

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

		    demoApi.del( '/wp/v2/posts/' + pid ).then( post => {
			console.log('"' + post.title.rendered + '" post is moved to trash.');
	            });
		});
	}
}

 

Conclusion

WordPress REST API hasn’t good default authorization (only cookies). For some more complex authorization, plugins are must. If you need authorization for development the best solution is default, cookie authorization and basic authorization through plugin. I hope this post will help you to understand process of OAuth1.0 with WP REST API. Thanks for reading, every comment is welcome. C ya in next part. 🙂

COMMENTS (8)

  • Zarko Dencic 4 months ago

    Why you had to disable security on Chrome? How this works on build app, I mean on real phone, since ionic is using webview?

    • ristapk 4 months ago

      Firstly, thanks for reading. Well, CORS on the server side is a problem, since I didn’t want to change anything here. On real phone, app will work fine, without any problem. I found a solution on IONIC blog here: http://blog.ionic.io/handling-cors-issues-in-ionic/

  • Pramod 4 months ago

    Good one. Make a post on oauth 2 also. Guide users to take free SSL via let’s encrypt.

    • ristapk 4 months ago

      Thanks, Pramod. I will write about that, also. Thanks for recommendations, again. C ya in next chapters.

  • Mark R S 4 months ago

    Hi Sir,
    Do u make customize WordPress plug-in Like customer area?
    If yes, how Much you charge pr. Hr?

    • ristapk 4 months ago

      Hi Mark,
      Yes, I make almost all kind of WP plugins and themes.
      About charging, we can discuss it with mails.
      Thanks for understanding 🙂

  • Pingback: My Homepage
  • Gilda 2 months ago

    excellent put up, very informative. I’m wondering why the other specialists of this sector do not notice this.
    You should proceed your writing. I’m sure, you have a great
    readers’ base already!

LEAVE A COMMENT