React and Axios get AWS client credentials - reactjs

I'm using latest version of react with axios and want to get an authentication token from aws / cognito. Therefore I have my client and client secret. When I send a curl request, it works as expected, but when I send the request via axios, I always get a status 405 response.
My code looks as follows:
...
axios({
url: 'https://xyz.amazoncognito.com/oauth2/token?grant_type=client_credentials',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'client_id': '***************',
'client_secret': '****************'
'redirect_uri': 'http://localhost:4200'
}
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
Instead of setting client_id, client_secret and redirect_uri to the headers, I added them in the url like
...grant_type=client_credentials&client_id=************&client_secret=*************&redirect_uri=http%3A%2F%2Flocalhost%3A4200
with the same result. Any ideas, what I'm doing wrong? As a side remark: I'm using axios for all my api requests and so I would like to stay at axios also in this case.
Thanks and kind regards,
Balu

You are not passing the required parameters correctly. Have a look at the example here:
https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
The required headers will be:
Authorization
If the client was issued a secret, the client must pass its client_id and client_secret in the authorization header through Basic HTTP authorization. The secret is Basic Base64Encode(client_id:client_secret).
Content-Type
Must always be 'application/x-www-form-urlencoded'.
The other information will be passed as request parameters.
This being said, you should not store your client and client secret on the client side (React application). If this is exposed on the client, anyone can get your client ID and Client secret and obtain a Cognito Token.

Related

Client does not receive cookies from server, postman does

There is a server, which serves my client react app at root path. So when I make any request to server from POSTMAN, to login for example, cookies are attached perfect. But when I make request from my client using AXIOS and withCredentials field as well, cookies ain't attached, nevertheless the request is sent good, but no cookies received. I don't think there is any reason to search issues in server code, because postman works with it perfect. In case, there is no CORS errors: server provides client app. I get nice response from the server, with no cookies. Postman gets them.
axios request in react app:
export const login = createAsyncThunk(
'auth/login',
async (credentials: ILogin) => {
// todo: making a request to server
const response = await axios({
url: '/api' + '/auth' + '/login',
method: 'POST',
data: credentials,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
},
});
console.log(response)
}
)
Client doesn't receive cookies, neither on localhost nor deployed app.
As you see, only place where cookies are shown it's network section in devtools, but everything else, including server acts like my second request hadn't any cookie, because in this case, server would answer like: agh, already logged in
P.S: i'm using http

API cs-cart put request by react and axios

I use react in front-end and cs-cart API in back-end.
In the following code I used axios.put() as follows:
const data = JSON.stringify({
"test1": "val1"
});
const config = {
method: 'put',
url: 'https://example.com/api/product/111',
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(res => {
console.log(res)
});
When sending a request, the browser sends a request with the OPTIONS method, which error: 405
Method Not Allowed returns.
And the original request (PUT) is not sent.
cs-cart is installed on the server. And the react project on localhost
Have you made sure to understand the error correctly i.e
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesnt support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Make sure that the server is able to understand how to interpret your request so the clients are able to proceed.
You can look at this in more detail below here.

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))

How to store JWT token in cookie React fetch

I am getting token from fetch method in React while I am sending appropriate credentials, but I don't know how to store JWT token in cookie, and later reused it. Below is code block:
fetch('http://localhost:5000/api/authenticate/login', {
method: 'POST',
headers: {'Content-type': 'application/json'},
body: JSON.stringify(loginInfo),
}).then(function (response) {
return response.json();
}).then(function (json) {
alert(json.token);
}).catch(function (ex) {
console.log("parsing failed", ex);
});
Rather than storing token in your browser, you should think about how to secure your connection properly.
If that's not the issue, you can store it in cookies or localStorage for what you will find plenty of tutorials on google. (I like this "hooks approach" in react)
But to use JWT token properly you should store send it in response as the HttpOnly cookie. See those implementations or nodeJS implementation
And the browser should attach the token on every new request on it's own. See here
To store a cookie in the browser use
document.cookie=`${cookieName}=${cookieValue};${cookieOptions}`
See specs here.
If you want to set the cookie from the server, use the set-cookie header, see here

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.

Resources