cakephp XMLHttpRequest post request csrf problem - cakephp

cakephp 4.4.6
I use vuejs as frontend, all works fine, but I have csrf problems to send XMLHttpRequest with post request.
CsrfProtectionMiddleware is activated.
It works fine when post data are send from an html "form" (_csrfToken is in a hidden field).
But if post data are send from an axios request, cakephp backend cannot get the csrf token.
Here is the front code:
axios
.post("/equipes/delete", {
headers: {
"X-Requested-With": "XMLHttpRequest",
'X-CSRF-Token': this.csrftoken,
},
params: {
// csrfToken: this.csrftoken,
// _csrfToken: this.csrftoken,
id: id,
},
})
.then((response) => {
})
.catch((e) => {
console.log(this.$options.name + ": method confirmationDelete : error");
});
The parameters send to the cakephp backend:
And the error returned :
Any ideas ?
Thanks

Related

Redirect from React ASP.NET application to SSO login page blocked by CORS Policy

My application is set up as of follows:
Frontend is React (SPA),
Backend is ASP.NET Core 6, and
User will be authenticated via SSO using SAML2 protocol (the SAML code is implemented on the ASP.NET side, not React)
When the React page is loaded, it will send a POST request via fetch API to the ASP.NET server which then will trigger to load the SSO page (I'm actually confused by this as I'm unsure how this would work with React since React handles all the routing piece here). However, I keep getting an error that is saying:
"Access to fetch at 'https://sso.example.com/saml/idp/profile/redirectorpost/sso?SAMLRequest=xxxx&RelayState=ReturnUrl%3D%252Fexample%252Fexampleapp%252FGetLoggedInUser' (redirected from 'https://forms.test.com/test/testapp/GetLoggedInUser') from origin 'https://forms.test.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
I attempted to fix this by changing the attributes in the fetch headers by all resulted in the same CORS error.
Here's my fetch api code on the frontend:
fetch("testapp/GetLoggedInUser", {
method: "POST",
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: data
}).then((response) => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
}
else {
return response.text().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
}
});
My backend (ASP.NET Core 6)
//[Authorize] is an attribute from Microsoft.AspNetCore.Authorization.AuthorizeAttribute
[Authorize]
[HttpPost("GetLoggedInUser")]
public string GetLoggedInUserData()
{
this.CheckSession();
Person Person = new ActiveUser(this.ID, GlobalVariables.ProcessCode);
dynamic P = Person.GetSimple();
User User = new User(this.WhitworthID);
P.LastAccess = DateTime.Now;
User.SetLastAccess();
return JsonConvert.SerializeObject(P);
}
Can anyone advise me on how to get past the CORS error when redirecting from React to the SSO page?
Modify your code to check if the response is redirected,if so redirect the browser to the new url.
fetch(url, { method: 'POST', redirect: 'manual'})
.then(response => {
// HTTP 301 response
// HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
if (response.redirected) {
window.location.href = response.url;
}
})
.catch(function(err) {
console.info(err + " url: " + url);
});

How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.
This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:
curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool
This is the React state hook for setting the data to the fetched data:
const [jiraTicket, setJiraTicket] = useState([]);
This is the fetch function for the API request (${} will be filled with user input):
function getJiraTicket() {
axios.get(`${username}:${apiToken}#Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
.then((res) => {
const data = res.data;
setJiraTicket(data);
})
}
The button inside the react component return should invoke the fetch function:
return(
<Container>
<Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
</Container>
);
This is the error I'm currently getting, because the authorization is not working the way I did it
(I replaced the provided username, API token etc. for this example):
GET http://localhost:3000/username:apitoken#https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)
Edit:
My current approach:
function getJiraTicket() {
axios.get(`${userName}:${apiToken}#https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
auth: {
username: userName,
password: apiToken,
},
withCredentials: true
})
.then((res) => {
const data = res.data;
console.log(data);
setJiraTicket(data);
})
.catch(err => {
// This error means: The request was made and the server responded with a status code
if(err.res) {
console.log(err.res.data);
console.log(err.res.status);
console.log(err.res.headers);
console.log("request was made and server responded with status");
// The request was made but no response was received
} else if (err.request) {
console.log(err.request);
console.log("request was made, but no response was received");
// Something happened in setting up the request that triggered an error
} else {
console.log("Error", err.message);
console.log("request is note set up correctly");
}
console.log(err.config);
})
Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"
Endpoint that works well in Postman (Basic auth is provided in Postman):
https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid
Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:
https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent
Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues
Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:
let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
baseURL: axiosUrl,
method: 'get',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin", "*"
},
//timeout: 2000,
auth: {
username: userName,
password: apiToken,
}
})
.then((res) => {
setJiraTicket(res.data);
})
.catch(function (error) {
console.log(error);
});

How to get response headers parameter from Axios get request?

I want to read the csrf token from the response header of the axios get request which I am going to send with the axios post request as request header. My code is as below :
const FileApi= {
list: (type:string,period:string): AxiosPromise<FilesL[]> =>
axios.get(`upload/${type}/${period}`)
.then(res=> {console.log(res.headers.get("X-CSRF-TOKEN"))}),
upload: (file:File,type:string,period:string): AxiosPromise<string> => {
return axios.post(`file/upload/${type}/${period}`,form,{
headers :{
'Content-Type':'multipart/form-data',
'token' : X-CSRF-TOKEN,
},
});
}
}
I am not able to get the token from the get request and so the post request is not functioning as the X-CSRF-TOKEN is undefined.
Should just be res.headers['X-CSRF-TOKEN']

Sails 1.4.0 CSRF Token sent from React App getting rejected 403

for the last three days I got stuck at this problem and it is getting very frustrating. I don't know what else to try.
I am running a Sails app on localhost:1337 and a create-react-app on localhost:3000.
I enabled csrf on the backend and followed the sails documentation to implement it.
I have created the route
'GET /grant-csrf-token': { action: 'security/grant-csrf-token' } and it works fine, I get the token. If I use postman the token is accpeted and my login form works.
In React however, I receive the token but I get 403 Forbidden error when I submit the post request to login.
useEffect(async () => {
let csrfToken;
try {
let csrfTokenRequest = await Axios.get(
`${state.serverUrl}/grant-csrf-token`
);
csrfToken = csrfTokenRequest.data["_csrf"];
dispatch({
type: "csrf",
value: csrfToken,
});
} catch (err) {
dispatch({
type: "flashMessage",
value: "There was an error.",
});
}
}, []);
I tried various ways to send the token with my post request:
await Axios.post(
`${appState.serverUrl}/login`,
{
emailAddress,
password,
_csrf: appState.csrf,
},
{ withCredentials: true }
);
I also tried setting it as a default header like so:
Axios.defaults.headers.post["X-CSRF-Token"] = appState.csrf;
and set cors allowRequestHeaders parameter to allowRequestHeaders: 'content-type, X-CSRF-Token',
I also tried sending it as a query parameter
`/login?_csrf=${encodeURIComponent(appState.csrf)}`
I also tried various cors settings inside Sails, currently it is setup like so:
cors: {
allRoutes: true,
allowOrigins: [
'http://localhost:3000',
],
allowCredentials: true
}
So just to clarify once again:
The /grant-csrf-token route works fine. I am receiving the token
It works in Postman
In React I get 403 error
Could you try something like that:
Send the csrf in header and allow Sails to process the request header.
// config/security.js
cors: {
allRoutes: true,
allowOrigins: ['http://localhost:3000'],
allowCredentials: true,
allowRequestHeaders: ['content-type', 'x-csrf-token', 'authorization'],
},

Can't access CakePHP API endpoint via ReactJS. Only through the browser

I am trying to build a REST API for my server via CakePHP. I thought I had it working as I can receive the JSON responses via the web browser however when trying to access the same route via ReactJS, the Controllers Action is not actually firing.
Reading the CakePHP docs I really should only have to implement these lines of code to get the API working (According to the docs) and I did:
/config/routes.php
Router::scope('/', function($routes) {
$routes->setExtensions(['json']);
$routes->resources('Users');
});
Here is the API Endpoint I want to hit:
`public function signUp() {
$file = fopen("error_log.txt", "w");
$txt = "firing endpoint";
$fwrite($file, $txt);
$fclose($file);
$response = $this->response;
$responseText = [
"status" => "200",
"message" => "User added successfully"
];
$response = $response->withType("application/json")
->withStringBody(json_encode($responseText));
return $response;
}`
Here I am successfully hitting that endpoint via the browser. My log message also appears in the error_log.txt file
Here is where I'm making a request via ReactJS:
handleRequest = () => {
console.log('making request');
axios({
method: 'get',
url: 'https://157.230.176.243/users/register.json',
data: {
email: this.state.email,
password: this.state.password
}
})
.then(function(response) {
console.log('got response');
console.log(response);
})
.catch(function(error) {
console.log('got error');
console.log(error);
})
.then(function(data) {
console.log('always executed');
console.log(data);
});
}
When I make this request via ReactJS I get a XHR failed loading: OPTIONS "https://157.230.176.243/users/register.json"
Also when making this request via ReactJS my log message does not get written to error_log.txt
Ok I finally figured out what was wrong. I have my React Development server running on
157.230.176.243:3001
and my CakePHP API served on that same server,
157.230.176.243
React didn't like it that I was passing the full URL of the API to the fetch()
call. I switched my React code to
url: "/users/register.json"
and it works fine.

Resources