How to retrieve Authorization header (rails / react app) - reactjs

Im banging my head and cant solve the mystery :(.
I've rails app and react, rails app returns Authorization bearer token in response header and also it returns Access-Control-Expose-Headers: Authorization
I see in the responses that everything is returned properly, but when I try to get value of Authorization header using response.headers.get('Authorization') Im getting null
My Fetch looks like:
fetch('/users/sign_in.json', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-CSRF-Token': token},
body: JSON.stringify({ user: values })
})
.then((response) => console.log(response.headers.get('Authorization')))
.then((data) => console.log(data))
What Im missing?
Ive checked cookies - rails does not save token into cookie, Im using devise-jwt gem. Thanks for any hint.

Problem solved...
When user signs in, in first response he gets Authorization header. I've tried sign in already signed user, and I'didnt get any proper header although in chrome debugger Authorization header was present in response :/

Related

Can't acces the Wordpress Api from a React website

I come to you in a time of great need. I've spent like a week on this and still can't figure it out. Please help.
Here is what I want to do:
I've got a WordPress website (http://test/test.wp/) on which you can do the following API call right in the browser when you are logged in:
$.ajax({
url: 'http://test/test.wp/wp-json/wp/v2/users/me',
method: 'GET',
beforeSend: function(xhr){
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
}).done(function(response){
console.log(response);
}).fail(function(response){
console.log( response.responseJSON.message );
});
And it works just fine. You get a Json about the current user (I just need the ID)
Now, I got another website (subdomain) written in React (http://app.test) and I am trying to pretty much do the same GET request to WordPress to grab the ID of the currently logged in User.
The sites are interconnected and I am sort of trying to imitate a SSO between WordPress and React by simply grabbing the ID of the currently logged in user in WordPress and using it in the react subdomain
To achieve this I've taken care of the CORS so I can make GET request from React to WordPress with no problems.
I also shared my WordPress wordpress_logged_in_cffb670352ad40cd796ad890d27ee701 cookie with the React subdomain so I've got access to that (which, from what I understand is the only cookie needed to keep you authenticated)
So, with all of that said why is my request from React failing?
Axios({
method: 'get',
url: 'http://test/test.wp/wp-json/wp/v2/users/me',
headers: {
'X-WP-Nonce': '659cbfeec0', // <= It's needed to use the WP Api and it's correct. I mannually grabed it from WP with wpApiSettings.nonce
withCredentials: true, // <= From what I understand is the only thing needed to send the `wordpress_logged_in_cffb670352ad40cd796ad890d27ee701` cookie ???
},
})
.then(response => console.log(response))
.catch(err => console.log(err));
So why then the answer that I get is a 403 (Forbidden)?:
code: "rest_cookie_invalid_nonce"
data: {status: 403}
statusText: 'Forbidden'
message: "Cookie verification failed"
You can say that the answer is in the response that I get, but I really have no idea why that's the case.
Please help.
Desperate Coder.
I was passing the 'with-Credentials' in the Headers and was not sending the cookies in the request because of that.
The correct way of doing it is:
Axios.get(
'http://test/test.wp/wp-json/wp/v2/users/me',
{
withCredentials: true,
headers: { 'X-WP-NONCE': 'Your_Nonce' },
}
)

HERE Geocoding API - not working inside my React app

I have a React app in which I use the HERE Geocoding API. I have an axios request to retrieve latitude and longitude and it does not work as well as expected. The request is not working inside my app
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`)
I have a 401 error. Bearer token invalid. Bearer missing or bearer value missing. If I open a new tab in my browser and paste the url https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey it works fine and I get the result I need.
I tried using the Authorization header
const config = {
headers: {
'Accept': 'application/json',
'Authorization': `apiKey myAPIKey`,
}
};
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`,config)
In the Authorization header, I tried with Bearer and Basic instead of apiKey
documentation HERE API
In the documentation about how to create an API Key and how to use it, the only thing I need to do is what I have already done. I have created a project, an API Key and I use it in my request.
HERE Geocoding API Key
I don't know how the HERE api works but the error message is probably the answer you are looking for.
You are likely to provide the api key via the Authorization header with your request. Read about the header on MDN
You just need to pass your API key in the link as a parameter.
Just sign up and you can get your API key.
https://developer.here.com/sign-up
The code should be like this.
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=${HERE_MAP_API_KEY}`,config)
The latest request would look like this.
axios.get(`https://geocoder.ls.hereapi.com/search/6.2/geocode.json?languages=en-US&maxresults=${maxResults}&searchtext=${query}&apiKey=${HERE_MAP_API_KEY}`)
.then(res => {
const data = res.data
console.log(data)
})
.catch(err => console.log(err))

axios returns 500 while postman returns 200

I am trying to call an api using axios but the problem is that it keeps returning 500 while postman is returning 200.
I've tried using fetch too but the result didn't change.
Here's my code and i hope you can help me out on this one.
and also i'm using a proxy in my package.json to get past the CORS erros.
let headers = {
'Authorization': 'a',
'Accept': 'application/json'
}
axios.get("v1/index-items", { headers: headers })
.then(res => {
console.log(res)
})
The problem can be in two things: wrong request URL, or CORS problems. In the second case, you need to configure CORS on your backend. Try to look at the headers on the response, are all needed headers there? Try to look in the developer console, there should be CORS error.

React - fetching from API, how to skip the cors response

I want to make a simple POST request from my React app to my Spring back-end to authenticate the user. What i am doing :
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
})
.then(response => response.json()).then(resposne => console.log(resposne))
Trying to make this call will get me a SyntaxError: Unexpected end of JSON input. If i log the response i can see that it is a response with a type:cors. I assume i am getting the response from the OPTIONS request that goes out. How can i skip that response? If i check the headers on the response, the header that i want to get, which is the Authorization header, is non-existant. If i go to chrome devtools - network section, and look at the response i am getting, i can see the resposne is as it should be, and i can even see the token returned in the Authorization header. How can i access that header in my React app? Server is properly configured since it returns the token, i just cant get it in the React app.
Thanks!
You should add the Access Control Expose Headers with the Authorization header like so:
Access-Control-Expose-Headers: Authorization
It doesn't seems an error on the token generation. Did you take a look on Response body?
Seems like the response body is not a valid json.

Authentication Error when using mode: no-cors using fetch in React

I am building a React app that is pulling different stats from services for our internal developers (commits, tracked hours, etc)..
I am using fetch to grab API data from Harvest, a time tracking app. According to their docs, you can use basic HTTP authentication. When I use the app Postman, all is well and I can see the response just fine. Initially I used:
getHarvest(){
// Set Harvest Headers
const harvestHeaders = {
method: 'GET',
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxx=',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
};
fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
.then( response => response.json() )
.then( projects => {
// Do some stuff
} )
}
This gives me an error in the console:
Fetch API cannot load https://myaccount.harvestapp.com/projects/.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. The response had HTTP status code 404. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
So with that feedback I changed the function to look like this:
getHarvest(){
// Set Harvest Headers
const harvestHeaders = {
method: 'GET',
mode: 'no-cors',
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxx=',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
};
fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
.then( response => response.json() )
.then( projects => {
// do stuff
} )
}
But that results in an Authentication error:
GET https://myaccount.harvestapp.com/projects/ 401 (Unauthorized)
I'm not sure how I can get the response correctly. Am I doing something wrong? It seems odd to me that using the app Postman works but this doesn't. Thoughts? Thanks!
It doesn’t seem like the Harvest API is meant to be used with XHR or Fetch from Web applications.
At least their docs don’t mention anything about using their API from XHR or Fetch, nor do those docs mention anything about Access-Control-Allow-Origin nor CORS in general.
Instead the docs give examples of using the API with curl and with the Postman REST Client.
And trying examples in the docs like below, the response has no Access-Control-Allow-Origin.
curl -H 'Content-Type: application/xml' -H 'Accept: application/xml' \
-u "user#example.com:password" https://example.harvestapp.com/account/who_am_i
So it seems like the answer is: You can’t access the Harvest API with XHR/Fetch from a Web app.
It works in Postman because Postman is not bound by the same-origin policy browsers enforce to prevent Web apps running in a browser from making cross-origin requests unless the site/endpoint the request is made to has opted in to using CORS (which it seems Harvest hasn’t opted into).

Resources