ValidateAntiforgeryToken failure - .net-5

I'm facing problem of AntiforgeryToken verification.
I'm sending data like this:
var data = {
__RequestVerificationToken: '#GetAntiXsrfRequestToken()',
Id: id,
ResolverGID: resolverGID
};
I'm using fetch method to send POST data
return fetch(fetchURL, JSON.stringify(data))
.then(async (response) => {
return response.json();
})
.catch(() => {
return false;
});
and sent data looks like this:
Id: 98
ResolverGID: "XXXX"
__RequestVerificationToken: "CfDJ8EaAHBfZaBJBuxJJzC77RytBbhcw-gV2E_x0mfFVVhCy0BSmE9L5w5jzIW-7CrY_pCClHed5Ez6D3vuDj5rWWyoKr90MSOu-uBMGUuoF9iIXQ9y4vUjY_sxa5fghGEo-Xcp5KC541aGD407Fz9D9itZMeID5jqRv61IRINTSwJH_2yRvgg-BC1cDAriut22Oyw"
but my method returns error 400: Bad request.
When I use [IgnoreAntiforgeryToken] instead of [ValidateAntiForgeryToken] attribute it works, but with antiforgery token validation it does not work.
When I use the same token function in modal window to send data it's ok, no problem occurs...
can somebody help me?
Thanks

Maybe I have found the solution to this.
[ValidateAntiForgeryToken] works only when FormData format is sent, so I had to send data like this:
let data = new FormData();
data.append('Id', id);
data.append('ResolverGID', resolverGID);
data.append('__RequestVerificationToken', '#GetAntiXsrfRequestToken()');
and then it works as expected.

Related

How can I save a response of HTTP GET Request in variable?

Here is my API code
#GetMapping("/api/test")
public String test() {
return "hello";
}
Then I will send request to this API by using ajax.
function test() {
$.ajax({
type: "GET",
url: "/api/test",
success: function(response) {
}
})
}
I want to save the value of ajax call response (In this case "hello") in variable. Please let me know how to do it.
Several ways of doing it !
As far as only a String message is concerned you can just store it like below
`var myResponse=response;`
Alternatively, you can also access values if response is an object (JSON reponse I mean)
for e.g. `var resp=response.message; //Assuming message is a key in response JSON`
For testing, use alert(response) or console.log(response) to see how your response is coming and manipulate accordingly !
Feel free to refer this link for detailed Ajax walkthrough https://www.tutorialspoint.com/jquery/jquery-ajax.htm
Hope these helps!

How do I get a specific column name values using Axios Promise-based Http Request in Vue.js and Laravel 8

If I do this in my Vue.js script component
getResumeAPIData(id){
// declare a response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data
console.log(this.RelationTable);
})
},
I get a response like this
{"id":1,"name":"userlocalvm","email":"userlocalvm#v","email_verified_at":null,"type":"user","bio":"Why","photo":"1606931001.jpeg","created_at":"2020-12-02T16:01:00.000000Z","updated_at":"2020-12-02T17:43:21.000000Z"}
Because of my Laravel api.php->Controller Backend code
$findOrFailId = Resumes::findOrFail($forEachId);
$foreignKeyOfResTable = $findOrFailId->user_id;
return User::findOrFail($foreignKeyOfResTable);
But if I do it like this as
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data.created_at
console.log(this.RelationTable);
})
The added dot then the property name of the column
response.data.created_at
I get a response
undefined
Sorry if this is a silly question as I am still quite a rookie in programming in general and the jargons that comes with it and I want learn and master javascript and php so bad!
It might be that the response is inside another data object. You might have to do something like this:
response.data.data.created_at

Can fetch be a substitute for AJAX?

I am wondering if it is possible to do in fetch all the things you can do in traditional ajax?
Because I'm having a problem with a simple login authentication using express. I want to send a response like Login error if the username/password is incorrect, or to redirect the user to the homepage if both is correct, to the client without refreshing the page.
I understand that you can do this in AJAX, but is it possible to do it in fetch also?
I tried using express js and sending a response through a json, but I can't figure out how to handle the response without refreshing the page.
I tried doing it like this in the express server
//if valid
res.json({
isValid: true
})
//if invalid
res.json({
isValid: false
})
And in the client side, specifically in the login page, I have this javascript that handles the submitting of the information
fetch('https://localhost:3000/auth', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
password
})
})
.then(response => response.json())
.then(data => {
//I understand that in this part, you can handle the response, but the problem is, I don't know how.
}
})
.catch(console.log)
You are SO close! You've got the fetch, then you've parsed it with response.json, so the next thing is the .then(). In that, you have the JSON object being passed into a param you've named data. All you need to do is check if that has the isValid property!
fetch('https://localhost:3000/auth', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
password
})
})
.then(response => response.json())
.then(data => {
if(data.isValid){
// Do something with a valid user. Redirect or whatever.
} else {
// Here, isValid is not set, or is false.
// Send them packing!
}
}
})
.catch(err => console.error("I died: ", err) );
ALSO, take a look at the .catch() block -- in the event of an error, that catches an Error thrown by either the fetch(), or a then(). So you need to add a parameter for the error, and a function body to handle that. I've edited my code sample to demonstrate.
Won't actually run here, but it's formatted all pretty.

Difficulty creating a functional Angular2 post

I'm trying to send a post request to another service (a Spring application), an authentication, but I'm having trouble constructing a functional Angular2 post request at all. I'm using this video for reference, which is pretty new, so I assume the information still valid. I'm also able to execute a get request with no problems.
Here's my post request:
export class LogIn {
authUser: string;
authPass: string;
token: any;
constructor(private _http:Http){}
onSubmit() {
var header = new Headers()
var json = JSON.stringify({ user: this.authUser, password: this.authPass })
var params2 = 'user=' + this.authUser + '&password=' + this.authPass
var params = "json=" + json
header.append('Content-Type', 'application/x-www-form-urlencoded')
this._http.post("http://validate.jsontest.com", params, {
headers: header
}).map(res => res.json())
.subscribe(
data => this.token = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
console.log(this.token);
}
}
The info is being correctly taken from a form, I tested it a couple of times to make sure. I am also using two different ways to build the json (params and params2). When I try to send the request to http://validate.jsontest.com, the console prints undefined where this.token should be. When I try to send the request to the Spring application, I get an error on that side:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Does anyone know what I'm doing wrong?
In fact you need to use the GET method to do that:
var json = JSON.stringify({
user: this.authUser, password: this.authPass
});
var params = new URLSearchParams();
params.set('json', json);
this._http.get("http://validate.jsontest.com", {
search: params
}).map(res => res.json());
See this plunkr: http://plnkr.co/edit/fAHPp49vFZJ8OuPC1043?p=preview.

How $http.get should work, I always get from PHP nothing right as answer

As I wrote in the title, I can't obtain any right answer from PHP. Anyone has any idea?
Javascript
var app = angular.module("appMovies", []);
app.controller("listMovies", ["$scope", "$http", function($scope, $http){
getMovies($http);
}]);
function getMovies(_http){
_http.get("movies.php", {data:{"getList":"LISTA"}})
.success(function(data, status, header, config){
console.log( data );
})
.error(function(data, status, header, config){
//console.log(data, status, header, config);
});
}
PHP
var_dump( file_get_contents("php://input") );
So, I got it... sorry my bad. Obviously $_GET fetch the data only from URL, so I should write
$http.get("movie.php/?getList=LISTA")...
It looks like you're mixing GET and POST requests. To use GET with Angular/PHP, you'll need to use params (query string parameters) instead of data (for POST bodies), and _$GET on the server (for query string parameters) instead of file_get_contents("php://input") (which gives POST body).
So in the browser, something like
_http.get("movies.php", {params: {"getList":"LISTA"}})
and on the server
var_dump($_GET);
Try it on another way:
$http.post("movies.php", {data: {"getList": "LISTA"}}).
success(function (_data, _status) {
})
.error(function (_data, status) {
});
And in your PHP-Code you can use then:
$postData = file_get_contents("php://input");
$request = json_decode($postData);
$request->_data;

Resources