Client does not receive cookies from server, postman does - reactjs

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

Related

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.

React and Axios get AWS client credentials

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.

Axios not authenticating to API

Ive been trying all day to get data from my Asp.Net Api but with no avail. I login and get an authentication token from the server and store it locally but when I try to perform any action that requires authentication, the server returns a 401 response. Is there something Im doing wrong in my code? When I use a tool like postman, everything works okay but not in my app.
This is my login
try {
response = await API.post(AuthUrl, credentials)
if(response.status >= 200 || response.status <= 299){
let Auth = {
Username: response.data.Username,
Roles: response.data.Roles,
Expires: response.data.Expires,
Token: response.data.Token
};
localStorage.setItem(window.location.host, JSON.stringify(Auth));
}
}
This is my axios encapsulator
export default axios.create({
baseURL: BaseUrl,
responseType: "json",
auth: `Bearer ${localStorage.getItem(window.location.host) == null? "" : JSON.parse(localStorage.getItem(window.location.host)).Token}`
})
and this is how im consuming it
try{
const response = await API.get(getUrl)
setLoading(false);
//........Do something with response
}
This is what is logged at the server
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44307/api/classes/getclasses/
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: CORS policy execution successful.
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executing endpoint 'SchoolManager.Web.Controllers.ClassesController.GetClasses (SchoolManager.Web)'
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "GetClasses", controller = "Classes", page = "", area = ""}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[SchoolManager.Dtos.Tenancy.ClassDto] GetClasses(System.String, System.String) on controller SchoolManager.Web.Controllers.ClassesController (SchoolManager.Web).
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: CORS policy execution successful.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes (Bearer).
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action SchoolManager.Web.Controllers.ClassesController.GetClasses (SchoolManager.Web) in 146.8824ms
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executed endpoint 'SchoolManager.Web.Controllers.ClassesController.GetClasses (SchoolManager.Web)'
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 218.2724ms 401
The way the axios.create method is used is not right.
Ref: https://github.com/axios/axios#request-config
The documentation clearly shows that config auth: indicates that HTTP Basic auth should be used, and supplies credentials. For Bearer tokens and such, use Authorization custom headers instead so in your case you can do something like this
export default axios.create({
baseURL: BaseUrl,
responseType: "json",
headers: {'Authorization': "bearer " + JSON.parse(localStorage.getItem(window.location.host)).Token}})

Flask session is not able to create cookies (using set-cookie response headers) on react front end application

Problem
I'm trying to use server side session (saved on PSQL db) but they are not persisting in between the requests.
Description
I'm running my application locally and is of two parts.
Backend running on MY_IP:2501
Frontend running on MY_IP:3000
Now as per my understanding, Flask saves the session in the "session" table of PSQL (since we are storing server side sessions) and the ID from that particular row is sent to the client in the form of a response header i.e. "Set-Cookie".
Every thing described above is working, but when the React frontend (or browser) receives this header it doesn't creates a cookie out of it because of which the session id is not stored in the frontend and then the frontend is unable to send the same to the backend due to which it is not able to fetch the associated session data resulting in empty session every time.
:(
Stuff I've tried so far..
Done allowing all type of headers while returning the response.
`response.headers.add('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept, x-auth")`
Done allowing the withCredentials header attribute from front end as well as backend.
Removed HttpOnly parameters from the session using "SESSION_COOKIE_HTTPONLY" config property
Done setting the "SESSION_COOKIE_DOMAIN" same as the front end
NOTE
If I call my API via POSTMAN the session is persisting as the cookie is saved in POSTMAN.
If I run the application on chrome --disable-web-security, then also it works.
Only configuration that is required:
Send the request (REST / GraphQL) with the header withCredentials = true.
Add Access-Control-Allow-Credentials = true headers from the backend.
On Axios (Frontend REST API).
import axios from 'axios';
export const restApi = axios.create({
baseURL: urlBuilder.REST,
withCredentials: true
});
restApi.interceptors.request.use(
function(config) {
config.headers.withCredentials = true; # Sending request with credentials
return config;
},
function(err) {
return Promise.reject(err);
}
);
On Apollo (Frontend GraphQL)
import {
ApolloClient,
ApolloLink
} from 'apollo-boost';
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
fetchOptions: {
credentials: 'include' . # Sending request with credentials
}
});
return forward(operation);
});
On Python-Flask (Backend)
#app.after_request
def middleware_for_response(response):
# Allowing the credentials in the response.
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response

React, Fetch-API, no-cors, opaque response, but still in browser memory

I've been trying to make an React site, which would fetch a GET-response from API and print it out to my .html-file. I've managed to fetch the file just right, but i can't access the JSON-data server sends me.
If i use no-cors in my Fetch-request, i get an opaque response containing pretty much nothing, but if i go to Developer tools i can find my data there and read it. If i do use cors, almost same thing. I get an 403-error, but my data is in the browser memory, but my code doesn't print it out. I can find the response from Network in developer tools.
Why does the server give me an error, but still i get my data? And how can i access it, if it's in the browser?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
EDIT: Error images after trying out suggestions
https://i.stack.imgur.com/wp693.png
https://i.stack.imgur.com/07rSG.png
https://i.stack.imgur.com/XwZsR.png
You're getting an opaque response, because you're using fetch with mode: 'no-cors'. You need to use mode: 'cors' and the server needs to send the required CORS headers in order to access the response.
Fetch is doing exactly what the documentation says it's supposed to do, from Mozilla:
The fetch specification differs from jQuery.ajax() in two main ways:
The Promise returned from fetch() won’t reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve
normally (with ok status set to false), and it will only reject on
network failure or if anything prevented the request from completing.
By default, fetch won't send or receive any cookies from the server,
resulting in unauthenticated requests if the site relies on
maintaining a user session (to send cookies, the credentials init
option must be set). Since Aug 25, 2017. The spec changed the default
credentials policy to same-origin. Firefox changed since 61.0b13.
So you need to use CORS, otherwise you get an opaque response (no JSON), and then 403 to me suggests that you haven't authenticated properly. Test your API with Postman, if I had to take a guess I'd say the API isn't sending the cookie because it's a GET request, so no matter how well you set your headers on the client it won't work. Try it as a POST instead. GET requests should really only be used to drop the initial HTML in the browser. I think for your headers use these, include the creds that the API sends and allow the domain to be different.
mode: "cors", // no-cors, cors, *same-origin *=default
credentials: "include", // *same-origin
Try this and see where is the error happening i believe in the parsing but lets check and see
fetch(https://#######/mapi/profile/, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "include"
})
.then((response) => {
console.log(response);
try {
JSON.parse(response)
}
catch(err){
console.log("parsing err ",err)
}
})
.catch((err)=>{
console.log("err ",err)
});
I had a similar issue, this kind of problem happend when a HTTP port try to send request to a HTTPS endpoint, adding a "mode:'no-cors'" doesn't do what is SOUND doing but rathere when the documentation says.
I fixed the issue by allowing in my API Application for calls from my HTTP port
(i'm using a .net 6 as an API in debugging mode, my code look like this https://stackoverflow.com/a/31942128/9570006)

Resources