I am working on Asp.Net core application and Application is running fine on my local but I am not able to validate Antiforgery token on the server.
Error: "Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted."
Below is the code.
#section scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#btnstart").click(function(e) {
let productvals = $("#productlist").val();
let runnumber = $("#runnum").val();
let btnval = $("#btnstart").val();
e.preventDefault();
$.ajax({
url: "#Url.Action("
CheckRunnumber ","
Validation ")",
type: "POST",
dataType: "json",
data: {
runnumber: $('#runnum').val()
},
success: function(data) {
if (data.success == "True") {
console.log(data);
console.log(data.btnstartval);
//$("#Runform").submit();
if ($("#Runform").valid()) {
console.log(productvals, runnumber, data.btnstartval);
console.log(gettoken());
$.ajax({
url: "#Url.Action("
RunCase ", "
CallService ")",
type: "POST",
dataType: "json",
data: {
products: productvals,
runnumber: runnumber,
button: data.btnstartval,
__RequestVerificationToken: gettoken()
},
contentType: 'application/x-www-form-urlencoded; charset=utf-8'
});
} else {
alert("Error");
e.preventDefault();
}
}
}
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
}
}
</script>
}
To compare this token I logged it on the console window and it is different then the one under Application tab inside the inspect window.
Below is the error log I am getting.
2020-10-08T13:00:05.5115395-05:00 0HM3BMFTTVJ22:00000001 [ERR] An exception was thrown while deserializing the token. (348bf365)
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
---> System.Security.Cryptography.CryptographicException: The key {dbeef040-4a73-45ff-8b62-064683015ea1} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)
2020-10-08T13:00:35.9439222-05:00 0HM3BMFTTVJ22:00000004 [INF] Process not found (d326d86c)
Do you host your application on shared server backend or else? It seems that your application doesn't have enough permission to read the key.
I suggest you could try to modify the IIS application pool identity to have enough permission to read the key. More details ,you could refer to below steps:
1.Open IIS management console:
2.Select your application pool
3.Modify the application pool identity to local system or other domain account which has enough permission to access your keys.
If this couldn't solve your issue, could you please share the startup.cs settings?
Related
I am developing a simple REST service in flask.
I have been trying to implement basic authorization.
Whilst, I can pass the username and password from the webpage using manual entry, I can't seem to read them from the header.
Here is my code:
On the server
def test():
if request.authorization and request.authorization.username == '***' and request.authorization.password == '***':
return "Authorized"
else:
return make_response('Authorization failed', 401, {'WWW-Authenticate': 'Basic realm ="Login Required"'})
On the client - using JavaScript
<script>
$(document).ready(function(){
$("#authButton").click(function(){
$.ajax({
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': "Basic " + btoa("***:***")
},
url: "********:5001/",
type: 'GET',
success: function(){
console.log("success");
},
error: function (){
console.log("error");
},
});
});
});
</script
>
I have also tried the Javascript code without the xhr fields section, but for neither do I get anything returned at all.
If I don't send the headers from the client it works and simply asks for manual input of the username and password.
All I'm trying to do is authenticate from the header.
Any pointers would be very gratefully received.
I wanna create a gist using GitHub API. I tried an POST ajax request:
var gist = {
"description": "Avatars",
"public": true,
"files": {
"check.txt": {
"content": "Avatars list..."
}
}
};
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(gist),
success: function(e) {
console.log(e);
},
error: function(e) {
console.error("Error!: ", e);
}
});
But I always get the following error:
jquery-3.1.1.min.js:4 POST https://api.github.com/gists 401 (Unauthorized)
Can anyone help me?
Thanks
When you want to edit things on Github, you need to authorize your request. Either by adding a username and password to the request or an oauth token.
More information can be found in the authorization documentation: https://developer.github.com/v3/auth/
Since I ran across the same problem recently, let me add the examples requested by T.Todua
If you want to authenticate with username and password, add the following lines to your $.ajax request:
crossDomain: true,
beforeSend: function (XHR) {
XHR.setRequestHeader(
'Authorization','Basic ' + btoa(Username + ':' + Password)
);
},
If, however, you created an access token for your gists (see Github help and don't forget to check the "Gist" permission!) then add the following lines instead
crossDomain: true,
headers: {
'Authorization':'bearer ' + GitHubAccessToken
},
The GitHubAccessToken will be shown once (and only once!) immediately after creation, so make sure to store it in a safe location as everybody knowing this access token will be able to modify your gists (until you revoke it again).
I am using twilio api code in jquery,its working fine.
but i want to implement it in pure javascript,how can i do that with only javascript?
My code is here.
$(document).ready(function() {
$("#btnSubmit").click(function(){
var SID = "AC654656****************"
var Key = "df5456**************"
$.ajax({
type: 'POST',
url: 'https://api.twilio.com/2010-04-01/Accounts/' + SID +'/Messages.json',
data: {
"To" : "+919580834781",
"From" : "+12018647238",
"Body" : "Test"
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(SID + ':' + Key));
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
can anyone please suggest me the solution?
Twilio developer evangelist here.
We do not recommend you use front end JavaScript to make calls to the Twilio API. It requires you to embed your Account Sid and Auth Token in your front end (or make it accessible from your front end) which means that an attacker could steal your credentials and use them to abuse your account.
We recommend you perform any actions with the Twilio API on the server. We do have a Node.js module on npm to make that easy to work with. Here's an example of sending an SMS message with the Node.js module:
var client = require("twilio")(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
client.messages.create({
body: "Hello",
to: TO_NUMBER,
from: FROM_NUMBER
}).
then(function(result) {
console.log("Message sent!");
}).
catch(function(err) {
console.log("Error sending message: ", err);
})
Check out this blog post introducing the Twilio Node.js module for more information.
Let me know if that helps at all.
I know a similar question has be asked but none helped in my case.
I am developing a Cordova app. I ran series of test on the app and everything (Navigation, Web Service call) works fine using my system browsers(IE and Mozilla)
Now using Eclipse, From the Emulator, I tried to log-in to the app (Authentication should invoke the webservice) but nothing happens.
On checking the LogCat I saw an Exception:
Uncaught SyntaxError: Unexpected token )", Source: File:///android_asset/www/login.html
Here is the .js script part:
$(document).on('click', '#S_IN', function() {
if (($('#username').val() == "") || ($('#password').val() == "")) {
alert("All fields are required.");
} else {
$.ajax({
type: "POST",
data: JSON.stringify({
"username": $('#username').val(),
"password": $('#password').val()
}),
url: "http://127.0.0.1/appName/Service.asmx/Authenticate",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (JSON.parse(data.d).toLowerCase() == 'success') {
$.mobile.changePage('main.html');
} else {
alert("Login failed. Invalid Username or Password combination.");
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
});
//..............................Login End........................//
Pls what am I doing wrong? I'm stuck.
Imaxo, your code style isnt so good, you need to do the follow things:
Procces data after DOM/window is loaded
declare variables
do not attach events to document(except keyboard events which should
fired without form)
prepare data before put it to request
and here is the small example:
firstFile.js
var app = app || {};
app.auth = (function(){
return {
initialize: function(){
//declare variable
//this.variable = global for this object
//var some; = local for this method
},
validate: function(){
//validate data
},
send: function(){
//send AJAX request
}
//other methods
}
})();
secondFile.js
var app = app || {};
$(function(){
app.auth.initialize();
});
this is revealing modular pattern with basic module organization pattern, but better look at require.js
asnwering your question, somewhere in your code you write excess ")"
Friends,
I know you have been facing these kind of question a lot.I was unable to find an answer even after a lot of google search.Well, lets come to the issue.
Requirement: Call a WCF Service GET API with basic authentication enabled using jquery ajax request.
Client side code:
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/Base64.js" type="text/javascript"></script>
<%--<script src="Scripts/jquery.base64.js" type="text/javascript"></script>--%>
<script type="text/javascript">
function make_base_auth(user, pass) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$(document).ready(function () {
var username = 'user';
var password = 'ppp';
var auth = make_base_auth(username, password);
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/javascript",
xhrFields: {
withCredentials: true
},
cache: false,
crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authentication", auth)
},
data: { 'inputData': "{PatientID:'12',FromDateTime:'05/21/2013 1:28:15 PM',ToDateTime:'05/21/2013 1:28:15 PM',ResponseType:'json',CompressResponse:'false'}" },
url:"http://192.168.15.160/RestAPI/Service.svc/GetMedicationValues",
success: function (jsonData) {
console.log(jsonData);
},
error: function (request, textStatus, errorThrown) {
console.log(request.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
});
</script>
Problem : I am getting login pop up when running the client application.I get the output only when i provide correct credentials on the pop up, irrespective of what credentials i pass in the request header.I have come through people asking this question a lot.Have anyone been able to solve this issue ? Thank You.
JSONP doesn't work with basic authentication.
If you don't need cross-domain request, use json as datatype.
Alos note that since JQuery 1.7, there are now two options for authentication : userName and password.
If the server performs HTTP authentication before providing a
response, the user name and password pair can be sent via the username
and password options.