How to get CSRF token Value at javaScript - javascript

I have requirement like that, when I send request, CSRF-token should be send with it. I Explore some SO questions, But I can't find Solution.
I have written Code like bellow to add token when request being sent,
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', "xyz12345");
//this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
return send.apply(this, arguments);
}
This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.
I have tried ajax function as below .
`
$.ajax({
type: "POST",
url: "/test/"
//data: { CSRF: getCSRFTokenValue()}
}).done(function (data) {
var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
if (csrfToken) {
var cookie = JSON.parse($.cookie('helloween'));
cookie.csrf = csrfToken;
$.cookie('helloween', JSON.stringify(cookie));
}
$('#helloweenMessage').html(data.message);
});
But it is not Yet Worked.
So my question is:
How to get js side CSRF-Token Value?

you need to do this in new Laravel
var csrf = document.querySelector('meta[name="csrf-token"]').content;
$.ajax({
url: 'url',
type: "POST",
data: { 'value': value, '_token': csrf },
success: function (response) {
console.log('value set');
}
});

I get my CSRF Token by this way,
By adding function :
$.get('CSRFTokenManager.do', function(data) {
var send = XMLHttpRequest.prototype.send,
token =data;
document.cookie='X-CSRF-Token='+token;
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token',token);
//dojo.cookie("X-CSRF-Token", "");
return send.apply(this, arguments);
};
});
Where CSRFTokenManager.do will be called from CSRFTokenManager Class.
Now It is adding token in header and cookie in every request.

Related

Unable to access JSONBin.io even I have added the Auth Headers

So, basically, I am trying to get data from JSONbin.io. I have set the RequestHeader before I send the request. As you see there's beforeSend and xhr.setRequestHeader("X-Master-Key", "$2b$10$QCzFeVffyq7vaiSBUfPbCeXUGV.IBpiHlWIOsDQAgj########");. But, it still say Error 401 aka unauthenticated request. I wondering if someone can help me with this. I also provide image that show that the headers is there.
Link: https://jsonbin.io/api-reference
Image: https://ibb.co/jGtFLk9
<script>
function getKey() {
$.ajax({
url: 'https://api.jsonbin.io/b/624efc9cd8a4cc06909d66cd/2',
type: "GET",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Master-Key", "$2b$10$QCzFeVffyq7vaiSBUfPbCeXUGV.IBpiHlWIOsDQAgj########");
},
success: function(data) {
const keyStore = data.keys;
var copyKey = document.getElementById("KeyDisplay");
document.getElementById('KeyDisplay').value = keyStore[Math.floor(Math.random() * 49)]
document.getElementById('Button').textContent = "Copied Key"
document.getElementById("Button").disabled = true;
copyKey.select();
navigator.clipboard.writeText(copyKey.value);
}
});
}
</script>
```
[1]: https://i.stack.imgur.com/zQxGv.png

ASP.NET Core Antiforgery Token without the form

Is it possible to have antiforgery tokens without forms? I have an ajax post call that I would like to make that needs an antiforgery token. However, most examples I have seen are asking for forms. This is what I have so far:
<script>
$(document).ready(function () {
var SessionId = document.getElementById("Id").value;
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
if (output[i].Mine == true) {
p.setAttribute("class", "Sender Me");
q.setAttribute("class", "Message");
} else {
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
}
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
return false;
});
</script>
This just gets its input from a textbox and a button that is not attached to a form.
Ajax request could send the anti-forgery token in request header to the server.Refer to solution in Handle Ajax Requests in ASP.NET Core Razor Pages.
<script type="text/javascript">
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
</script>
<script>
$(document).ready(function () {
var SessionId = document.getElementById("Id").value;
var form_data = {
"SessionId": SessionId
};
var headers = {};
headers['XSRF-TOKEN'] = gettoken();//header name could be changed
$.ajax({
url: "/Home/testPost",
method: "POST",
data: JSON.stringify(form_data),
headers:headers,
contentType: "application/json",
success: function (result) {
console.log(result);
//...
},
error: function (error) {
console.log(error);
}
});
//...
});
Then you need to configure the antiforgery service to look for the XSRF-TOKEN header you have defined:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
Of course,you need to use correct model binding and [ValidateAntiForgeryToken] attribute for your action.
The AntiforgeryToken is there to prevent cross site request forgery. So you should really use it. The easiest way to get one in jQuery is to render a dummy, hidden form on the page. Then the you can use your javaScript to copy the token from the dummy form and include it in your ajax post.
You need to add it manually. Try this:
var token = $("[name='__RequestVerificationToken']").val();
And then post it with your data:
data: {
__RequestVerificationToken: token,
JSON.stringify(form_data)
}
EDIT:
As #AndresAbel mentioned, you can copy the token from the form and send it in ajax post:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
}
Then in in your script:
var token = $('input[name="__RequestVerificationToken"]', $('#__AjaxAntiForgeryForm')).val();
Then send it in ajax:
data: {
__RequestVerificationToken: token,
JSON.stringify(form_data)
}
Don't forget to add the annotation [ValidateAntiForgeryToken] for your method in the controller.

Calling Outlook API to Add event to outlook calendar using ajax call

I need to Add an event from my database to outlook calendar for which I have been trying to make an ajax call to the outlook auth API first which looks like this
$scope.authorizeOutlook = function () {
let redirect = 'http://localhost:51419';
let clientId = 'xxx';
var authData = 'client_id=' + clientId + '&response_type=code&redirect_uri=' + redirect + '&response_mode=query&scope=https%3A%2F%2Fgraph.microsoft.com%2Fcalendars.readwrite%20&state=12345';
debugger
$.ajax({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
type: 'POST',
host: 'https://login.microsoftonline.com',
contentType: "application/x-www-form-urlencoded",
contentLength: "600",
data: authData,
success: function (response) {
debugger;
alert(response.status);
//alert("success");
},
error: function (response) {
alert(response.status);
//alert("fail");
}
});
}
But I am getting response status as 0. What does that mean? Where am I doing it wrong?
If you use Oauth2.0, you need to add " token-type: Bearer ".
Reference from:
Get access tokens to call Microsoft Graph

Get hold of json content that is being sent to Jquery

That's how I reach when I send some values that are specified in my input and therefore they need to send to a API.
When I try to send them to the monkey, my monkey tells me that nothing has been sent.
At my console.log(token), it tells me what data is available and I also agree that it all fits together. But the problem is just that it has to come over to my API.
function PayStripe() {
// Open Checkout with further options:
handler.open({
name: 'XXX ',
description: 'XX abonnement',
currency: "dkk",
amount: $('#HiddenPrice').val() * 100,
email: $('#Email').val()
});
};
// Close Checkout on page navigation:
$(window).on('popstate', function () {
handler.close();
});
var handler = StripeCheckout.configure({
key: 'pk_test_xxxx',
locale: 'auto',
token: function (token) {
token.subscriptionId = $('#SubscriptionId').val();
token.City = $('#City').val();
token.Postnr = $('#Postnr').val();
token.Mobil = $('#Mobil').val();
token.Adresse = $('#Adresse').val();
token.CVRVirksomhed = $('#CVRVirksomhed').val();
console.log(token.subscriptionId);
console.log(token);
$.ajax({
type: "POST",
url: "/api/Stripe",
contentType: "application/json",
data: token,
success: function (data) {
//window.location.href = '/Subscriptions/Succes';
alert(data + "Succes")
},
error: function (data) {
console.log(data + "Error");
},
dataType: 'json'
});
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
Where the problem lies is that the API is by no means able to get informed information from jquery. so it's like it can not / will receive it.
[HttpPost]
[Route("api/Stripe")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromForm] JObject token)
When I grab the token that I need for example. then I do this here:
var SubscriptionId = (int)token.GetValue("subscriptionId");
When you set contentType: "application/json", you need to stringify the data to json yourself
data: JSON.stringify(token),

Getting an AJAX GET request to work with Express.js

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500
When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;
I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});

Categories

Resources