OAuth1.0a ionic2 client cannot connect to wp-api server


#1

I am using crypto and oauth-1.0a from nmp in ionic2 application. I want to access WP-API which is correctly set to handle authentication, I tested this using Postman.

Http.Get results in the following error:

{"_body":{“isTrusted”:true},“status”:0,“ok”:false,“statusText”:"",“headers”:{},“type”:3,“url”:null}

The options generated that I pass as argument to Http.Get are as follows:

{“method”:0,“headers”:{“Authorization”:“OAuth oauth_consumer_key=”",
oauth_nonce=“jSZGPwkj4quRGMb0bhBLYKwmc3BGfrQw”, oauth_signature=“x3zseS3XTFBLMsNDLXC4byn2UDI%3D”,
oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1522414816”,
oauth_token="",
oauth_version=“1.0"”},“body”:null,“url”:"",“params”:{“rawParams”:"",“queryEncoder”:{},“paramsMap”:{}},“withCredentials”:null,“responseType”:null}

Part of code:

this.oauth = new OAuth({
      consumer: {
        key: this.apiconstant.consumerkey,
        secret: this.apiconstant.consumersecret
      },
      signature_method: 'HMAC-SHA1',
      hash_function: hash_function_sha1,
      realm:''
    });
    let request_data = {
      url: '<API url>',
      method: 'GET'
    };

let token={
      key: this.apiconstant.token,
      secret: this.apiconstant.tokensecret
    }
//This part doesn't seem to work
this.authkey = this.oauth.authorize(request_data,token);
    this.keyoauth = new URLSearchParams();
    for (let param in this.authkey) {
      this.keyoauth.set(param, this.authkey[param]);
    }

let options = new RequestOptions({
      method: 'GET',//request_data.method
      url: '<API url>',
      headers: this.oauth.toHeader(this.oauth.authorize(request_data,token)),
      search: this.keyoauth
    });

this.http.get('<API Url>',options)
      .map(res => res.json()).subscribe(data=>{
        console.log('Resulting data' + JSON.stringify(data));
      },
      error=>{
        console.log('Got error'+JSON.stringify(error));  
      });

//Error part executed

What am I missing here? I’m testing my app on android device. Without authentication I get desired results from the WP-API (Wordpress), that is if the Oauth is disabled on WP-API.

Please help! This is my second day on this. I should also let you know I’m new on these technologies but I’m able to research and understand how they work.


#2

Please edit your post, it is not very readable at the moment.
Use the </> button above the input field to format your code, command line output or error message (select the text first, then click the button or wrap it in ``` manually). Check the preview if it looks better. This will make sure your text is readable and if it recognizes the programming language it also automatically adds code syntax highlighting. Thanks.

Also from skimming your post it wasn’t really clear what the actual error or problem is.


#3

The issue is not related to ionic packages. After research I can see it is caused by preflight being blocked.


#4

I worked on something similar today, I needed to set it up roughly as follows to have my request authenticated. (The code in the example is a bit more verbose for clarity)

import { HTTP }              from '@ionic-native/http'
import OAuth                 from 'oauth-1.0a'
import CryptoJS              from 'crypto-js/'

...
...

const consumer = {
  key: YOUR_CONSUMER_KEY,
  secret: YOUR_CONSUMER_SECRET
}

const token = {
  key:    YOUR_TOKEN_KEY,
  secret: YOUR_TOKEN_SECRET
}

const hashFunction = (baseString, key) => {
  return CryptoJS.HmacSHA1(baseString, key).toString(CryptoJS.enc.Base64)
}

const oauth = new OAuth(
  {
    consumer:         {
      key:    consumer.key,
      secret: consumer.secret
    },
    signature_method: 'HMAC-SHA1',
    hash_function:    hashFunction,
    nonce_length:     6,
    version:          '1.0',
    realm:            ''
  })

const request = {
  url:     endpoint,
  method:  'GET',
  params:  {},
  headers: {}
}

const oauthObject = oauth.authorize(request, token)

request.params = {
  oauth_consumer_key:     oauthObject.oauth_consumer_key,
  oauth_nonce:            oauthObject.oauth_nonce,
  oauth_signature:        oauthObject.oauth_signature,
  oauth_signature_method: oauthObject.oauth_signature_method,
  oauth_token:            oauthObject.oauth_token,
  oauth_version:          oauthObject.oauth_version
}

request.headers = oauth.toHeader(oauthObject)

this.http
    .get(request.url, request.params, request.headers)
    .then(data => {
      console.log(data.data) // data received by server
    })
    .catch(error => {
      console.log(error.error) // error message as string
    })

My signature kept being mismatched until I set up the request params (second argument for http.get) exactly like this.


My target is to submit WordPress post in custom post type from Ionic App using wp restapi
My target is to submit WordPress post in custom post type from Ionic App using wp restapi