Set cookies automatically csfr and session from sanctum in sveltekit - laravel

I'm doing a login with laravel/sanctum and sveltekit, when I submit the form,first inside the actions I execute first a fetch to the csfr endpoint from sanctum ('/sanctum/csrf-cookie') but in the reponse the cookies are not set automatically in the browser but cookies arrive.So how i can set automatically?
Here the code :
`export const actions: Actions = {
default: async ({ request, fetch, cookies }) => {
const formData = await request.formData();
const user = {
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password'),
password_confirmation: formData.get('password_confirm')
};
await fetch('http://localhost:8000/sanctum/csrf-cookie', {
method: 'GET',
credentials: 'include'
});
const res = await fetch('http://127.0.0.1:8000/api/register', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
// 'X-XSRF-TOKEN': '' || ''
},
body: JSON.stringify(user)
});
const data = await res.json();
console.log(data);
}
};`

Related

Cypress sends request twice to the backend

I have the following test
let rxId = "";
let basketAuthToken = "";
let basketId = "";
let replacedBody = "";
cy.fixture(`payload/${ordersPostPayload}`).then((Body) => {
cy.readFile(`temp/resultIdFile.json`).then((resultIdFile) => {
Id = resultIdFile.lastSucceededRxId;
basketAuthToken = resultIdFile.baskets[0].authToken;
basketId = resultIdFile.baskets[0].basketId;
cy.log(`the value of the read value is ${Id}`);
replacedBody = JSON.stringify(Body).split(`$Id`).join(Id);
cy.writeFile(`temp/ordersPostPayload.json`, replacedBody);
cy.request({
method: "POST",
url: `https://***/ops/orders`,
headers: {
"Content-Type": "application/json",
Channel: "**",
"EsbApi-Subscription-Key": `****`,
"Accept-Language": `en-US`,
"basket-token": basketAuthToken,
"basket-id": basketId,
redirectUrl: "****/evaluate-payment",
cancelUrl: "****/evaluate-payment",
},
body: replacedBody,
failOnStatusCode: false,
}).then((response) => {
cy.writeFile("temp/result.json", response);
});
});
});
The request is sent to the backend. On cypress GUI the request is just fired once. but when I check the backend I can see two requests.

I am having trouble integrating my twilio video api through react hooks, specifically for the videochat.js

webpage; videochat.js; room.js
const handleSubmit = useCallback(async event => {
event.preventDefault();
alert('Work');
const data = await fetch('./video/token', {
method: 'POST',
body: JSON.stringify({
identity: username,
// room: roomName
}),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json());
setToken(data.token);
}, [username, roomName]);
This is the part where I am likely having an issue (lines 18-32 of videochat.js)

react axios 401 unauthorized and sometimes 403

I'm building a react native app post requesting laravel php api. it works on postman but not on Axios. Do you know how can i solve? I can't post a form data
I tried other forms sending post request of Axios. but none of them is solution
axios({
method: 'post',
url: 'URL',
params: {
"api_token": token,
"name": "talha"
},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}).then(response => alert(response)).catch(err => console.warn(err))
-----
const serverURL = "URL";
const http = axios.create({
timeout: 1000,
baseURL: serverURL,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false,
cache: false,
dataType: "jsonp"
});
data is a formdata
await http.post("/passengers", data, config)
.then(Response => alert(Response.data))
.catch(error => console.warn("hata", error))
-----
axios.post( 'URL',
data,
{
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
alert('SUCCESS!!');
})
.catch(function(){
alert('FAILURE!!');
});
postman script:
https://pastebin.ubuntu.com/p/vS54dytpCQ/
You can use my API helper function for batter development.
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
const api = async (url, method, body) => {
/**
* config object for fetch
*/
const config = {
method: 'get',
baseURL: 'BASEURL WILL BE HERE',
url,
headers: {
'Content-type': 'application/json',
authorization: await AsyncStorage.getItem('auth_token'),
},
};
if (method) {
config.method = method;
}
if (body) {
config.data = body;
}
let response;
try {
response = await axios(config);
return {...response.data};
} catch (e) {
throw new Error(e.message);
}
};
export default api;
Then use this function
import api from 'filpath';
const functionName = async () => {
try{
const res = await api('/passengers', 'POST' posData);
console.log(res.data);
} catch(e){
alert('FAILURE!!')
}
}
Note: Save the auth token to AsyncStorage when user login.

File upload with fetch API vuejs returns 419 unknown status

I am using VUE.js with Laravel to upload file using fetch api. I have added the csrf token to the header of the request, but still getting the 419 unknown status. Any help will be appreciated thanks.
Here is the JS of the component
<script>
export default {
name:'UploadModal',
data(){
return {
image:'',
ext:'',
file:''
};
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.file = files[0];
this.createImage(files[0]);
},
uploadArtwork: function () {
let formData = new FormData();
formData.append('artwork', this.file);
fetch(this.$parent.itemUrl, {
method:'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
'X-CSRF-TOKEN' : Laravel.csrfToken
}
})
.then(res => res.json())
.then(res => {
alert(res);
})
.catch(e => console.log(e));
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
}
}
</script>
I know this is an old question, but I ran into this issue as well when using fetch and the linked answer (Laravel 5.5 ajax call 419 (unknown status)) did not help, since that relates to jQuery's Ajax method.
For those who are facing the same issue, it looks like this is due to the default credentials setting (defaults to "omit"), which essentially omits the csrf header for some reason. You can get around this by changing credentials to "same-origin" or "include" depending on your needs.
Example:
fetch("/leads", {
method: 'POST',
credentials: "same-origin",
headers: csrf_header
}).then(res => res.json())
.then(
(json) => {
this.setState({
isLoaded: true,
items: json.leads.data,
sort: json.sort,
search: json.search,
sort_by: json.sort_by,
filter: json.filter
});
}
);

Session cookies do not change using ajax and nodejs server

I want to change a session cookie after an asynchronous request but no matter what I tried I keep failing.
My request is as follows:
$.ajax({
type: "POST",
url: "/setStatus",
data: { userId : _userId, token: _token, tokenSecret : _tokenSecret, service : service, loggedIn : _loggedIn, authorized : _authorized },
xhrFields: { withCredentials: true },
crossDomain: true
}).done(function(reply) { alert('finished'); });
Setting the session variables on the server.
exports.setStatus = function(req, res)
{
req.session.userId = req.body.userId;
req.session.token = req.body.token;
req.session.tokenSecret = req.body.tokenSecret;
req.session.service = req.body.service;
req.session.loggedIn = req.body.loggedIn;
req.session.authorized = req.body.authorized;
res.header('Access-Control-Allow-Credentials', 'true');
res.writeHead(200);
};
The setting on the server are as follows:
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat', store: new RedisStore({ host: 'localhost', port: 3000, client: dbcon })}));
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
I forgot to mention that on simple requests the session cookies change as expected.
Any ideas?
You should call req.session.save() after the modifications if you are doing it with ajax.
exports.setStatus = function(req, res)
{
req.session.userId = req.body.userId;
req.session.token = req.body.token;
req.session.tokenSecret = req.body.tokenSecret;
req.session.service = req.body.service;
req.session.loggedIn = req.body.loggedIn;
req.session.authorized = req.body.authorized;
req.session.save(); // This saves the modifications
res.header('Access-Control-Allow-Credentials', 'true');
res.writeHead(200);
};

Resources