Invalid signature Open Bank Project Oauth1.0a - react-native

I'm developing a React-Native App with Open Bank Project and I can't use suggested SDKs, not even the nodeJS one as Oauth1.0 is not available in RN.
And I'm stuck with a Bad Signature error on Access Token request '/oauth/token' after passed '/oauth/initiate' and '/oauth/authorize' without any problem.
As specified in docs here before accessing to a Protected Resource we need an Access Token via a POST Request, which gives me the Bad Signature answer.
Here is my code for the request:
getAccessToken(verifier){
let request = {
url: 'https://api.openbankproject.com/oauth/token',
method: 'POST',
data: {
oauth_verifier: verifier,
oauth_token: this.auth.oauth_token,
oauth_token_secret: this.auth.oauth_token_secret
}
}
return fetch(this.url_login, {
method: request.method, //POST
form: request.data,
headers: this.oauth.toHeader(this.oauth.authorize(request))
})
.then((res) => {return res.text()})
.then((txt) => {
console.log('setUID', txt, this.url_login, {
method: request.method,
form: request.data,
headers: this.oauth.toHeader(this.oauth.authorize(request))
})
})
Here is the signed request:
Object {method: "POST", form: Object, headers: Object}
form:
oauth_token:"..."
oauth_token_secret:"..."
oauth_verifier:"71531"
headers:
Authorization:
"OAuth oauth_consumer_key="...", oauth_nonce="3UlQ5dx958tibf6lSg0RUGPQFZeV7b8V", oauth_signature="weyE1lFkoIjAErYLKdSi9SDlCZsNBi7%2BuAkLV2PWePo%3D", oauth_signature_method="HMAC-SHA256", oauth_timestamp="1464248944", oauth_token="...", oauth_token_secret="...", oauth_verifier="71531", oauth_version="1.0""
I've tried with and without Oauth_token_secret, also moving oauth_verifier from body to query but with the same Bad Signature result.
Any idea? thx

You can use oauth module https://github.com/ciaranj/node-oauth
var oauth=require('oauth');
var consumer = new oauth.OAuth(
"https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token",
_twitterConsumerKey, _twitterConsumerSecret, "1.0A", "http://127.0.0.1:8080/sessions/callback", "HMAC-SHA1");
then generating signature like this :
var parameters = consumer._prepareParameters("user_access_token", "user_access_token_secret", "http_method", "request_url");
var headers = consumer._buildAuthorizationHeaders(parameters);
parameters array contains signature, also you can build authorization headers if needed. Hope it helps :)

Related

Request body missing from POST requests made using Postman scripting

I am trying to run a pre-request script for authenticating all my requests to the Spotify API. It works via the Postman GUI, but when I try to make the request via scripting, it fails because there is no body. Here is my code
const postRequest = {
url: pm.environment.get("spotifyAuthApi"),
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"Content-Length": 29,
"Authorization": "Basic " + btoa(pm.environment.get("client_id") + pm.environment.get("client_secret"))
},
body: {
grant_type: "client_credentials",
}
}
I get a
error: "unsupported_grant_type"
error_description: "grant_type parameter is missing"
And when I examine the request via the postman console, there is no request body, even though the request was built exactly like my fetch token request that does the same thing successfully in postman, only via the GUI instead of via a pre-request script. I have searched far and wide about this issue and tried multiple variations of the body object but to no avail. Either the body object doesn't generate my desired field, or it doesn't get created at all.
Mode might be missing in the body object. Try this:
body: {
mode: 'raw',
raw: JSON.stringify({ grant_type: 'client_credentials' })
}
More details might be found in Postman docs for RequestBody.
If you're using urlencoded, the body of the request would be structured like this:
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'grant_type', value: 'client_credentials'}
]
}

Auth0 refresh token in React Native fails with 401

In my React Native app -- init app not Expo -- I'm trying to refresh the access_token but my POST call is failing with 401. I'm testing this functionality so I make the POST call some 30 seconds after I login so not sure if this plays a role or not.
In my initial login, I do get a refresh_token along with a valid access_token. I then tell my app to wait 30 seconds and make a POST call that looks like this:
const url = 'https://mydomain.auth0.com/oauth/token';
const postOptions = {
method: 'POST',
url: url,
headers: {
"content-type": 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'refresh_token',
client_id: 'MY_CLIENT_ID',
refresh_token: 'REFRESH_TOKEN_RECEIVED_DURING_LOG_IN'
}
};
fetch(url, postOptions)
.then((response) => {
debugger;
// this is where I get response.status 401
})
Any idea what the issue is here?
Also want to mention that under my application settings, Refresh Token is checked under "Grant Types" but refresh token rotation or expiration are NOT enabled.
I figured this out and sharing it in case others need it in the future.
First, Auth0 documentation is misleading at best. They keep mentioning a regular POST call which doesn't work.
In my React Native app, I use their react-native-auth0 library. This library does offer a refreshToken() method which is what I ended up using.
Before I share the code, here are a couple of really important points:
Be sure to include offline_access in the scope of your initial authentication call for the user. Without including offline_access in your scope, you won't get a refresh_token. Once you receive it along with your access_token and id_token, store it as you'll use it many times. This brings me to the second point.
Unless you set it otherwise, your refresh_token doesn't expire. Therefore, store it some place secure and NOT just in AsyncStorage. As mentioned above, unless, you set it otherwise or it gets revoked, your refresh_token doesn't expire and you use it again and again.
With that said, here's the code. Please keep in mind that at start up, I initialize auth0 as a global variable so that I can access it in different parts of my app.
Here's what my initialization looks like in index.js:
import Auth0 from 'react-native-auth0';
global.auth0 = new Auth0({
domain: "MY_DOMAIN.auth0.com",
clientId: "MY_CLIENT_ID",
});
And here's how I use the refreshToken() method:
// First, retrieve the refresh_token you stored somewhere secure after your initial authentication call for the user
global.auth0.auth.refreshToken({ refreshToken: 'MY_REFRESH_TOKEN' })
.then(result => {
// If you're doing it right, the result will include a new access_token
})
you probably need to add the authorization header with your access_token:
const url = 'https://mydomain.auth0.com/oauth/token';
const postOptions = {
method: 'POST',
url: url,
headers: {
"content-type": 'application/x-www-form-urlencoded',
"Authorization" 'bearer '+access_token,
},
body: JSON.stringify({
grant_type: 'refresh_token',
client_id: 'MY_CLIENT_ID',
refresh_token: 'REFRESH_TOKEN_RECEIVED_DURING_LOG_IN'
});
};
fetch(url, postOptions)
.then((response) => {
debugger;
// this is where I get response.status 401
})

Unable to generate OAuth 2.0 Access Token from Office365 via JavaScript

I'm trying to pull an access token from Office365's /token identity platform endpoint via OAuth 2.0 client credentials grant flow. I have my app registered, the client ID & secret, etc...
I can make the POST request in Postman and receive the access token without issue:
However, when I try the POST request via JavaScript (by way of Google Apps Script), I receive an error message: AADSTS900144: The request body must contain the following parameter: 'grant_type'
I've already Google'd this error and found a bunch of different solutions, and have tried implementing them to no avail. I imagine this has to do with the URL encoding, but cannot figure it out.
Code:
function getO365() {
// POST Request (To get Access Token)
var tenantID = 'longstringhere'
var appID = 'longstringhere'
var appSecret = 'longstringhere'
var graphScore = 'https://graph.microsoft.com/.default'
var url = 'https://login.microsoftonline.com/' + tenantID + '/oauth2/v2.0/token'
var data = {
'client_id': appID,
'scope': graphScore,
'client_secret': appSecret,
'grant_type': 'client_credentials'
};
var postOptions = {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
'body': data,
'redirect': 'follow'
};
var authToken = UrlFetchApp.fetch(url, postOptions);
}
The only real difference between my code and the JavaScript Fetch code I pulled off of Postman is:
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "longstringhere");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "longstringhere");
urlencoded.append("grant_type", "client_credentials");
When I try to use URLSearchParams in Google Apps Script, I keep getting this error: ReferenceError: URLSearchParams is not defined
Any ideas? Thanks in advance!
This was resolved by changing 'body' to 'payload' for UrlFetchApp per the documentation. Edited code to reflect the change. Credit to #TheMaster for pointing out my mistake.
'payload': data,//from 'body': data,

Unable to get access Token linkedin Oauth

I know some will put comment like this post is duplicate of so many questions, but I've tried many ways to achieve Access Token in linkedin Oauth. Explaining what i tried.
1) I'm following it's official doc's Linkedin Oauth2
2) I'm successfully getting Authorization code from step 2 and passing that code to step 3 for exchanging Auth code for getting Access Token. But i'm getting following error
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}
3) According to some links i need to set content-type in the header.Link which tells to set content-type is missing
4)Then i tried calling https://www.linkedin.com/uas/oauth2/accessToken this service instead of POSt to GET. And passing data as queryParams.
5) Some link says oauth code expires in 20 sec, So i've checked, i'm making call for access token in less that 1 sec.
6) And if i pass data in Body params like as below and used url as https://www.linkedin.com/uas/oauth2/accessToken
var postData = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
client_id: 'my_client_id',
client_secret: 'secret_key'
};
7) With Get call my url i tried
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+authCode+'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key
Still i'm getting Error even though status code is 200, i'm getting that error(with GET api)
and If POSt by passing postData in body i'm getting bad request 400 status code
Not understanding why m I not getting access code. I've read many solutions.
Sharing code as requested.
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast"
], function (Controller, MessageToast) {
"use strict";
return Controller.extend("OauthTest.OauthTest.controller.View1", {
onPress: function (evt) {
var sPath =
'https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=my_client_id&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&state=DCEeFWf45A53sdfKef424&scope=r_basicprofile';
window.location.href = sPath;
var oRouter = new sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("View2", {
"username": "Test"
});
MessageToast.show(evt.getSource().getId() + " Pressed");
},
//after user allows access, user will be redirected to this app with code and state in URL
//i'm fetching code from URL in below method(call is happening in max.569ms)
onAfterRendering: function () {
var currentUrl = window.location.href;
var url = new URL(currentUrl);
var authCode = url.searchParams.get("code");
if (authCode !== undefined && authCode !== null) {
var postData = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
client_id: 'my_client_id',
client_secret: 'secret_key'
};
/* var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=' + authCode +'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key';*/
var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
$.ajax({
url: accessTokenUrl,
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
},
data: postData,
success: function (data, textStatus, jqXHR) {
console.log(data);
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
alert('error');
}
});
}
}
});
});
Help will be appriciated..!!!
Finally I am happy to post my answer after so much search.
Every step I did is correct only, but one thing I was missing here like, Linkedin API doesn't supports CORS.
I tried implementing Javascript SDK, that works like charm. But API wasn't.
Then I found very helpful Link which says I need to implement Rest API from backend by allowing CORS, not from front end.
Make sure to follow all the points which I mentioned above in my post.
And for Allow CORS follow this link. You will get data but only basic profile of user according to LinkedIn Terms data can be accessible
Hope this post may help someones time to search more

Worklight 6: Authenticating using Adapter against a webservice

I have an authentication webservice sitting at http://example.com:9080/auth/login that accepts a POST request with www-url-form-encoded encoding and responds back in JSON format.
I am currently going through the Adapter-based Authentication tutorial. Inside the body of submitAuthentication(username, password) in SingleStepAuthAdapter-impl.js, I have the following:
function submitAuthentication(username,password):
var input = {
method: "post",
path: '/auth/login',
returnedContentType: 'json',
body: {
content: JSON.stringify({"username":username, "password":password}),
contentType: "application/x-www-url-formencoded;charset=utf-8"
}
var returnData = WL.Server.invokeHttp(input)
The problem I am having is that the server (locally hosted websphere) is not receiving my username and password. Am I missing something here?
You could add a header to the request with basic authentication credentials such as:
var input = {
method: "post"
returnedContentType: 'application/json',
path: path,
headers: {
'Authorization': 'Basic '+ base64_encode(username+':'+password),
You could also make the request and then store a secure cookie and attach it as a header on future requests following this post:
Attaching cookie to WorkLight Adapter response header