Get token to call post to firebase database in react-native - firebase

I have a firebase database and i need to do a classic post call, but i have a problem with token.
For example, in firebase for get user i use app().auth().currentUser.uid,
for a classic get list i use app().firestore().collection('prizes') and it work.
so, to get user token i do app().auth().currentUser.getIdToken()
and for post i do
export function postData(endpoint: string, data: any, token) {
return fetchJson(ENDPOINT_API + endpoint}, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token ? token : USER_TOKEN}`,
},
})
}
and result is
{"error":"Token invalid","message":"Cannot destructure property type of 'undefined' or 'null'."}
the token comes back to me, but I don't know if it's the correct way

This line:
Authorization: `Bearer ${token ? token : USER_TOKEN}`,
Replace it by:
'Authorization': `Bearer ${token ? token : USER_TOKEN}`,

Related

Getting ugcPost details through rest/posts api?

I could not get the ugcPost of a post or comment, the urn looks like: urn:li:ugcPost:7023566176156811264,7023567581345140736
how to use this in the api rest/posts/{ugcPosts urn}
the API returns the error {
"message": "Could not find entity",
"status": 404,
"code": "NOT_FOUND"
}
I have also added the headers
{
Linkedin-Version: 202210,
X-RestLi-Protocol-Version: 2.0.0
}
but it is still returning the same error even though I have encoded the urn, example:
https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264?viewContext=Reader
You need to add a bearer token in the header. And viewContext=Reader params is not required as per my knowledge of the documentation. I am sharing a sample example.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264',
headers: {
'X-Restli-Protocol-Version': '2.0.0',
'LinkedIn-Version': '202208',
'Authorization': 'Bearer [your_bearer_token]',
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
You can visit this link for more information.

Strava authorization working on local host but not when published to azure

The following code authorizes my strava account in my web app:
function Authorize() {
document.location.href = "https://www.strava.com/oauth/authorize?client_id=xxxxx&redirect_uri=https://localhost:44389/home/strava&response_type=code&scope=activity:read_all"
}
const codeExchangeLink = `https://www.strava.com/api/v3/oauth/token`
function codeExchange() {
fetch(codeExchangeLink, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: '#ViewBag.cId',
client_secret: '#ViewBag.cSec',
code: '#ViewBag.code',
//need to do this to get a new refresh token that 'reads all' and issues a new Access Token - refer to comments below
grant_type: 'authorization_code'
})
})
.then(res => res.json())
.then(res => getActivities(res))
}
However, when I publish to azure and change the document.location.href code and redirect address (as below) to match my published app it fails with a 'bad request' error.
document.location.href = "https://www.strava.com/oauth/authorize?client_id=xxxxx&redirect_uri=https://xxxx.azurewebsites.net/home/strava&response_type=code&scope=activity:read_all"
Error is included below:
{"message":"Bad Request","errors":[{"resource":"Application","field":"redirect_uri","code":"invalid"}]}
Any help greatly appreciated
This was totally my error (embarrassingly). The issue was in my Strava Api App Settings, my call back uri was set to the default 'developers.strava.com'. All I had to do was change it to match my Published Web App uri 'xxxx.azurewebsites.net/home/strava' and it now works.

ClientFunction: _axios2 is not defined

I'm running TestCafe for UI automation, using ClientFunctions to trigger API requests (so that I can pass along session cookies).
Currently I have a ClientFunction with fetch which works fine... except we're now testing IE 11 and Fetch is unsupported.
Fetch code:
const fetchRequestClientFunction = ClientFunction((details, endpoint, auth, method) => {
return window
.fetch(endpoint, {
method,
credentials: 'include',
headers: new Headers({
accept: 'application/json',
'Content-Type': 'application/json',
}),
body: JSON.stringify(details),
})
.then(httpResponse => {
if (httpResponse.ok) {
return httpResponse.json();
}
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
However when I try to switch it to axios... not so much:
import axios from 'axios';
const axiosRequest = ClientFunction((details, endpoint, auth, method) => {
return axios({
method,
auth,
url: endpoint,
data: details,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 3000,
})
.then(httpResponse => {
if (httpResponse.status < 300) return httpResponse;
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
Tried using window.axios, and also passing axios as a dependency. I've also tried making the axios request without the ClientFunction... and despite getting response of 200, the website wasn't updated as expected.
Each time I either get _axios2 is not defined or window.axios is not a function. I would greatly appreciate some guidance here.
TestCafe ClientFunctions allow only serializable objects as dependencies. You need to have axios on the client side to send such a request.

Token based auth for aspnet-core web api

Dears,
I've followed https://stormpath.com/blog/token-authentication-asp-net-core
to authenticate the user for my web apis
I managed to create a successful access-token when calling api/token
My problem is the use of [Authorize], authorize filter didn't get that my user has a valid token, although HeaderAuthorization and HeaderExpries have been set.
function getValues()
{
$.ajax({
url: "http://localhost:48146/api/values",
headers: { 'Authorization': 'Basic ' + accessToken, Expires: tokenExpires },
method: "GET",
context: document.body,
success: function (data) {
alert(data);
}
});
}
Did I passed a wrong header?
Based on the tutorial you followed you should pass a bearer authorization header, not a basic authorization header:
headers: { 'Authorization': 'bearer' + accessToken, Expires: tokenExpires },
I've figured out 2 problems
as #user1336 said in header I had theaders: { 'Authorization': 'bearer' + accessToken, Expires: tokenExpires },
I had to call ConfigureAuth(app) before app.UseMvc(); in Startup.css

Meteor PayPal Payments (using Meteor.http)

Edit: I've fixed my original problem and have shown a metor example in my answer.
I'm getting a error 500 when trying to get the token for my PayPal API app in Meteor:
token = EJSON.stringify(Meteor.http.call "POST", "https://api.sandbox.paypal.com/v1/oauth2/token",
headers:
"Accept": "application/json"
"Accept-Language": "en_US"
auth: "user:pass"
params:
"grant_type":"client_credentials"
);
console.log("Token: "+token);
Output of this code:
Token: {"statusCode":500,"headers":{"server":"Apache-Coyote/1.1","date":"Fri, 15 Mar 2013 05:04:43 GMT","content-length":"0","connection":"close"},"data":null,"error":{}}
Obviously PayPal is returning a error 500 to me. I can't figure out what may be causing this. Of course Auth is actual data, not user:pass.
Why am I getting error 500?
Edit: Compiled Javascript
var token;
token = EJSON.stringify(Meteor.http.call("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", {
headers: {
"Accept": "application/json",
"Accept-Language": "en_US"
},
auth: "user:pass",
params: {
"grant_type": "client_credentials"
}
}));
console.log("Token: " + token);
Here's an example implementation to make paypal API calls with meteor.
In the startup of your program, fetch your token. Always replace clientid and clientsecret with your own.
token = EJSON.parse(Meteor.http.post("https://api.sandbox.paypal.com/v1/oauth2/token",
headers:
"Accept": "application/json"
"Accept-Language":"en_US"
auth: "clientid:clientsecret"
params:
"grant_type":"client_credentials"
#encoding: "base64"
).content).access_token;
Now, create a payment, shown here in a Meteor.methods method (and returning a URL for the client to go to):
buySingleItem: () ->
console.log "Starting new payment, user id: "+Meteor.userId()
result = Meteor.http.post("https://api.sandbox.paypal.com/v1/payments/payment",
headers:
"Authorization":"Bearer "+token
"Content-Type": "application/json"
data:
{
"intent":"sale"
"redirect_urls":
"return_url":"http://mysite.herokuapp.com/done",
"cancel_url":"http://mysite.herokuapp.com/cancel"
"payer":
"payment_method":"paypal"
"transactions":[
{
"amount":
"total":"3.00",
"currency":"USD"
"description":"My item description."
}
]
}
)
payment = result.data
console.log "PayPal redirect: "+payment.links[1].href
return payment.links[1].href
This will create a PayPal checkout style payment, within Meteor.
I would provide sample code, but I'm not familiar with Meteor.
Basically you have 2 issues here:
in your headers, you are not passing the client id or client secret. This should look like:
Authorization: Basic clientid:clientsecret
Also, in your request, your request should look like this:
response_type=token&grant_type=client_credentials
Looks like your in json then stringifying it, so whatever way you need to get the POST request I just put up there, once you get it, you should be good.
[edit]PayPal's doc's dont have you base64 encode the client id or secret[/edit]
Then, when you need to execute the payment you can do as below. See the whole payment process here.
Meteor.methods
'executePaypalPayment': (payerId) ->
payment = PaypalPayments.findOne({ userId: #userId },
{ sort: { 'create_time': -1 } })
token = Meteor.call 'getPaypalToken'
url = 'https://api.sandbox.paypal.com/v1/payments/payment/' +
payment.id + '/execute'
res = Meteor.http.post url,
headers:
Authorization: 'Bearer ' + token.access_token
'Content-Type': 'application/json'
data:
payer_id: payerId
payment = res.data
payment['userId'] = #userId
if payment.state is 'approved'
# we insert the sucessful payment here
PaypalPayments.insert payment
return if payment.state is 'approved' then true else false

Resources