Angular-5 StripeConnect -303 Error -Response for Preflight is invalid (Redirect) - angular5

I am doing StripeConnect(Standard Account Type) with Angular 5 and Asp.NetCore.
I am able to get redirected to required URL with code={} value.
When I am trying to use this code in below URL,
https://connect.stripe.com/oauth/token\client_secret={{secret test key}}\code={{code}}\grant_type = authorization_code"
1.I get preflight is invalid (Redirect) error in browser from my angular solution.
2.The html for stripe login page from Postman.
The code I wrote for making the post call to above URL (in angular) is :
getCredentialsFromStripe(code: any)
{
let Url = "https://connect.stripe.com/oauth/token";
//\client_secret=" + {{key}} + "\code=" + code + "\grant_type
= authorization_code";
return this.http.post(Url, {
Body: "client_secret = {{key}}\code =" + code,
Headers: {
'Authorization': 'Bearer '+ code,
"Accept": "application/json; charset=UTF-8",
"Access-Control-Allow-Origin": "https://connect.stripe.com/oauth/token"
}
}).map(res => res.json());
}
As per suggestions on internet,I tried making the post call from backend(.NET core(2.0) API for me),but didn't get through in creating account for standard account type.
Moreover testing from postman is giving the full html page of login ,instead of getting this object:
{
"token_type": "bearer",
"stripe_publishable_key": "{PUBLISHABLE_KEY}",
"scope": "read_write",
"livemode": false,
"stripe_user_id": "{ACCOUNT_ID}",
"refresh_token": "{REFRESH_TOKEN}",
"access_token": "{ACCESS_TOKEN}"
}
Can anybody give me a lead on this.I have been stuck past two days.
Any thoughts will be really appreciated.

Well,I was able to fix it. Instead of creating accounts using the URL (given above) in angular project (following the node.js documents),I called the stripe api's in Asp.net core (my api solution) and called them.It worked easily.

Related

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,

Axios POST status 400 bad request [duplicate]

This question already has an answer here:
Getting error when using axios POST
(1 answer)
Closed 3 years ago.
I am trying to make a POST request to the spotify web api. I am using this piece of code for doing so:
axios.post(ACCESS_URL, {
"grant_type": 'authorization_code',
"code": code,
"redirect_uri": REDIRECT_URI
},
{
headers: {
"Authorization": "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
'Content-Type': 'application/x-www-form-urlencoded'
},
})
In the snippet above code is the users authorization code and everything else are server constants. The problem is that I am getting the following error when I am performing the request:
error: 'unsupported_grant_type',
error_description: 'grant_type must be client_credentials, authorization_code or refresh_token'
As you can see, the grant type that I am sending in the request body is one of the 3 specified grant types, but I am stil getting status 400 and I can't figure out why. Any ideas?
Thanks in advance since I am sure it's a silly question with an easy answer, but I just don't see it
See Unsupported grant type error when requesting access_token on Spotify API with Meteor HTTP for a similar problem.
Spotify expects the grant_type in the query string parameters, not in the post request body. Actually the configuration in the above question/answer looks pretty similar to the axios config. Simply wrap your first three parameters into a params object:
axios.post(ACCESS_URL, {
params: {
"grant_type": 'authorization_code',
"code": code,
"redirect_uri": REDIRECT_URI
},
headers: {
"Authorization": "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
'Content-Type': 'application/x-www-form-urlencoded'
}
})
I found the solution. I had to encode the data using querystring like this:
return axios.post(ACCESS_URL,querystring.stringify({
"grant_type": 'authorization_code',
"code": code,
"redirect_uri": REDIRECT_URI
}),
{headers: {
"Authorization": "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
'Content-Type': 'application/x-www-form-urlencoded'
}
}
)
Thanks everyone for the help

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

Couchdb Vue.js authentication

I'm trying to move a node/express authentication application over to vue.js. I am able to successfully authenticate getting a 200 code. However, the response returned from couchdb does not contain the "set-cookie" header, which contains the much needed AuthSession token. The code that I am using in my Vue component is:
var reqBody = "name="+user+"&password="+pass;
var reqBodyLength = reqBody.length;
console.log(reqBodyLength);
this.$http.post('http://localhost:5984/_session/', reqBody, {headers: {'Content-Type' : 'application/x-www-form-urlencoded', 'Accept' : 'application/json'}}).then(response => {
console.log("response: " + JSON.stringify(response));
console.log("response.headers: " + JSON.stringify(response.headers));
console.log("response.headers.set-cookie: " + JSON.stringify(response.headers["set-cookie"]));
}, response => {
alert('you unauthorized, fool!')
})
Has anyone ever had an issue getting the "set-cookie" header?
Thanks, Tyler
Couch's AuthSession is HttpOnly cookie and therefore can't be accessed through a client side script. But the cookie itself should be set to a browser by that _session query, so all the consequent requests will be authorized.
BTW, /_session also accepts JSON payload, at least in CouchDB 1.6, so the query doesn't have to be in x-www-form-urlencoded form.

OAuth Post Request Failing

I've got everything working up until Step 2 of the OAuth process where you request the actual token. I'm using a very simple jQuery Post request and constantly getting Access Control Origin errors. I've tried contentType: 'application/json' and everything else I know to try.
It's just not working and I'm not sure the problem. I've confirmed all the variables are set properly before the request. Simple post request...
var url = 'https://[STORENAMEVARIABLE].myshopify.com/admin/oauth/access_token';
var data = JSON.stringify({ client_id: apiKey, client_secret: secret, code: code });
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
debugger;
},
error: function(data) {
debugger;
}
});
Any ideas what I'm doing wrong?
You need to make your OAuth requests from a server. This is the Javascript cross-domain security kicking in.
If you are using Rails you can use omniAuth and it'll take care of the whole OAuth dance for you. Otherwise you'll have to search around but most popular language have an OAuth library that you can just plug in.