How to send a POST request to Firebase REST API in react - reactjs

I'm trying to sign in with OAuth credentials which involves issuing an HTTP POST request to the Auth verifyAssertion endpoint. How would I go about doing this syntactically? I'm trying to follow this firebase documentation but they use curls for the examples.
https://firebase.google.com/docs/reference/rest/auth/#section-sign-in-with-oauth-credential
The endpoint is https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=[API_KEY]

You can either choose the native fetch api with
window.fetch('https://url-you-want-to-post-to.com/', {method: 'POST', body: { //body data } })
or you can use a third-party library like axios (although you need to npm install it first and then import it)

Related

React native Axios Django - Csrf failed referer checking failed no referer

I am calling a Django back-end api from React front-end using axios.
For that api which is login api, I am using Django Knox package in logic.
React.js - I am calling axios.request(method, url, data) and the api call is working correctly.
When I went to Developer tools>Network, I can see Referer header set to React.js website in request header and no other csrf-related header. In Response headers I can see two set-cookie headers, csrftoken and sessionid.
React Native - same way I am calling api but api returns error csrf failed referer checking failed - no referer . When I checked response.config, Referer header is not set unlike React.js
Curl - works fine
httpie - works fine
How can I get rid of this error.
Note 1 - My Django back-end is based on api token logic and not csrf in any way.
Note 2 - React.js and Django are hosted on different domains. I am facing error in React Native which is in debug mode.
Update 1 - After disabling CSRF middleware in Django settings.py, now I am getting only one setCookie header (csrftoken is no longer obtained) but same error still persists.
Django Rest api need a Referer header.
In case of React.js it is automatically set (maybe by browser) and its value is current website.
But in case of React Native, it is not set. so we have to manually set it.
From this link, i set Referer header in axios. see below code
export const axiosAPICall = (method,url,data,headers) => {
let request = {
method: method,
url: url,
};
if (data) {
request['data'] = data;
}
if (headers) {
request['headers'] = headers;
}
// Referer is auto-set in react.js as same website value.
// for react-native we have to set it manually to target api:port
request['headers'] = {
...request['headers'],
Referer: url
}
return axios.request(request)
.then(res => res.data)
.catch(error => {throw error});
};
In Django settings.py, I commented CSRF middleware
In Django settings.py, I added only TokenAuthentication class to remove SessionAuthentication.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
Note - Please do steps 2 and 3 at your risk after knowing your requirements properly. I removed CSRF middleware because my API was completely dependent on token for auth. I did not need CSRF in any way.

Send request to Airvisual API with Postman

I am using react and use axios for making request to the airvisual API. However when I made the request in localhost it returned with a 404 status (I registered to Airvisual and got the key). I read Airvisual documentation and it mentioned using postman to make the request so I download postman and tried it out and the request is now success. I do not understand why it does not succeed in the first place and if I have to use postman for that API call, how do I connect it with my localhost.
Here's the code:
componentDidMount() {
axios
.get(
'api.airvisual.com/v2/countries?key=c441738e-dbc0-4f06-babc-bb126a29c19f'
)
.then((response) => console.log(response));
}

React app using API with another origin (CORS)

I have a react app, which uses a java ee backend rest server, running on another domain. I have enabled CORS:
Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Headers : origin, content-type, accept, authorization
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age : 1209600
I am using react with fetch like this:
export function get(path, headers) {
return fetch(apiUrl + path, {
"metod" : "GET",
"headers" : headers,
"credentials" : "include"
})
}
My react app is running on http://localhost:3000.
When I am logging in, the server returns the Set-Cookie, but the cookie is not included in any further request to the server, unless I try to log in again. Then it is included for that specific login request.
Any suggestions?
I just want to share how I make my local development painless by this post if you are using create-react-app by just adding your main API url proxy to your package.js for example "proxy": "http://localhost:8080/API"
No need to setup CORS on your backend.
Install this.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=es
Once installed, click on his BrowserIcon and toggle on. It is all. You will not receive more error.
EDIT. Solution for Production
If you want config it from your server (or simply not adding a browser extension, try this:)
If you are using node.js do the following: node.js server file: response.writeHead(200, { 'Content-Type': contentType, 'Access-Control-Allow-Origin': '*' })
fetch('http://ajax.googleapis.com/ajax/services/feed/load?v=‌​1.0&num=8&q=http://r‌​ss.cnn.com/rss/editi‌​on_entertainment.rss‌​?output=rss', { method: 'get', mode: 'no-cors', }).then(() => { console.log('Works!'); });
Other solution:If you are using PHP too you can add: <?php header('Access-Control-Allow-Origin: *'); ?> into your PHP File. As I see, it is not the case, so... In your server (eg: Apache) add this directive: Header set Access-Control-Allow-Origin * in Settings (as the first option).
So, I solved the problem by using another stackoverflow thread and robertklep's comment. As stated here: "When working on localhost, the cookie domain must be omitted entirely.". I implemented robertkleps idea, but did not set the domain. It resulted in a Set-Cookie like this: Set-Cookie:kek=7fukucsuji1n1ddcntc0ri4vi; Version=1; Path=/; Max-Age=100000. This works fine.
To add more on existing answers.
With react you can use "proxy" in your package.json to avoid CORS.
Basically if you need to reach localhost:8100 (your java backend) and your react app run on localhost:3000
You can set:
In your package.json
"proxy": "http://localhost:8100"
And then when you want to make a get to /hello which would be an endpoint of your java API you can do:
import axios from 'axios';
axios.get('/hello')
.then(resp => {
console.log(resp.data);
});
And it will be redirected to http://localhost:3000/hello so you will avoid CORS.

Angular with wordpress jwt auth

I'm trying to make wordpress as a backend to my angularjs app, so I'm using the plugin rest-api with the jwt-auth
so when trying to login I get the following error
XMLHttpRequest cannot load http://localhost/back/wp-json/jwt-auth/v1/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://imider.ma' is therefore not allowed access. The response had HTTP status code 500.
I know i have to add CROS access, but I'm not familiar with wordpress, so any help?
https://docs.google.com/document/d/17zgUHZrvL5KVG2yKQE8NWgxNZn6V08xr65DBox5WVZ0/edit?usp=sharing
here is my tutorial of how to access the api
then you can use this to get the token
$http({
method:'post',
url:'',
data: {
username: '',
password: ''
}
}).then(function(results){
console.log(results);
})
then you can use this
$http({
method:'get',
url:'',
headers: { 'Authorization': 'Bearer <myTokenId>' }
}).then(function(results){
console.log(results);
})
I created a video detailing the process of installing and setting up the plugin. If you follow the steps I outlined there you should be good.
https://youtu.be/Mp7T7x1oxDk
The idea is that you also need to modify .htaccess and wp-config.php to make the plugin work with the existing API endpoints as well.
Just by installing the plugin and adding a SECRET_KEY, used to sign the token will make the JWT setup work but it will not allow you to use the tokens generated through that API with the existing REST API endpoints.

Authenticated API access to Firebase via REST API

This is surprisingly excruciating. There's no documentation whatsoever for the new Firebase + Python. So I'm trying to use the REST API, which needs a special kind of authentication.
As you can see, they say it could be the app's secret (nowhere to be found in the new console) or the authentication token (which is not documented for python). If I click the REST authentication documentation I get a Java example.
I've downloaded the JSON Key file for the service account, and tried to apply pieces of code found in other places, unfortunately in vain.
Can anyone provide a hint on how to proceed with this?
You need to generate an access token from the service account JSON key file using the Google API Python client library, and then add it to the headers of your request.
Here's an example of how to do it with requests
from oauth2client.service_account import ServiceAccountCredentials
import requests
import json
import httplib2
scopes = [
'https://www.googleapis.com/auth/firebase',
'https://www.googleapis.com/auth/userinfo.email',
"https://www.googleapis.com/auth/cloud-platform"
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'/pathto/json_file.json', scopes)
headers = {"content-type": "application/json; charset=UTF-8"}
headers['Authorization'] = 'Bearer ' + credentials.get_access_token().access_token
firebase_url = "https://docs-examples.firebaseio.com/rest/saving-data/fireblog/users/alanisawesome/name.json"
data = {
"name": "Alan Turing",
"birthday": "June 23, 1912"}
requests.put(firebase_url, headers=headers, data=json.dumps(data).encode("utf-8"))
You can install the google python api client library using pip:
pip install --upgrade google-api-python-client

Resources