google invisible reCaptcha server side validation is failing - javascript

i have integrated the invisible reCaptcha in my application and the client side response is coming as part of solving the image challenge. i am then calling a angular function to validate user response on server side using below code. where onloginSubmit(token) is the success call back.
<button id="btnLogin" ng-disabled="loginForm.$invalid"
class="g-recaptcha primarybtn margin-left-zero form-control-input"
data-sitekey="{{public_key}}"
data-callback='onloginSubmit'>{{'label_login' |
translate}}</button>
<script>
function onloginSubmit(token) {
angular.element(document.getElementById('loginForm')).scope().verifyReCaptcha(token);
};
</script>
in angular i am calling the verifyReCaptcha as below.
$scope.public_key = "------ My Site Key -------";
$scope.private_key = "------ My Secret Key -------";
$scope.verifyReCaptchaURL = "https://www.google.com/recaptcha/api/siteverify";
$scope.verifyReCaptcha = function(reCaptchaToken){
var captchaData = {
secret : $scope.private_key,
response : reCaptchaToken
}
$http({
headers: {
'Accept': 'application/json,text/plain',
'Content-Type': 'application/json;application/x-www-form-urlencoded;charset=utf-8;',
},
url: $scope.verifyReCaptchaURL,
method: 'POST',
data: captchaData
}).success(function (data) {
console.log("success");
$scope.login();
}).error(function (data) {
console.log("error");
$window.location.reload(true);
});
};
when i hit the api service https://www.google.com/recaptcha/api/siteverify . i get the below error.
Failed to load https://www.google.com/recaptcha/api/siteverify: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405.
i couldnt find more documentation for the issue.
what is it that i am doing wrong and also if there is any error the recaptcha does not come up and the login button which i am using fails to respond.
n the request i am mentioning the Method as Post, the method is over ridden as Options and the request payload which i am sending is not present. this is what i got in the networks tab
Request URL:https://www.google.com/recaptcha/api/siteverify
Request Method:OPTIONS
Status Code:405
Remote Address:10.120.118.50:8080
Referrer Policy:no-referrer-when-downgrade

Most of the thing you did a great job. One thing is to require in your application is communicate to an external domain so you can include HTTP header content type is include a JSONP format.
$http({
headers: {
'Accept': 'application/json,text/plain',
'Content-Type': 'application/jsonp;application/x-www-form-urlencoded;charset=utf-8;',
},
url: $scope.verifyReCaptchaURL,
method: 'POST',
data: captchaData
}).success(function (data) {
console.log("success");
$scope.login();
}).error(function (data) {
console.log("error");
$window.location.reload(true);
});

Related

How to call web API with GET method basic authentication into jquery() in javascript

Hello I am using this method to read this api it giving CORS error. I have added CORS plugin with chrome then also it is not coming. Please let me know how to solve these to error.
text:
function NoCors() {
debugger;
var uName = "*****";
var passwrd = "*****";
document.write("Enter1");
var url = 'http://219.90.67.163:8207/api/Info/getgismeterdata'
$.ajax({
type: 'GET',
url: url,
crossDomain: true,
//Access-Control-Allow-Credentials: true,
contentType: 'json',
datatype: "application/json",
headers: {
"Authorization": "Basic QXBpVXNlcjpBcGlQYXNz",
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName + ":" + passwrd));
},
success: function (data) {
debugger;
console.log("data")
//Success block
},
error: function (xhr, ajaxOptions, throwError) {
//Error block
},
});
}
error in console:
1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
2. Access to XMLHttpRequest at 'http://219.90.67.163:8207/api/Info/getgismeterdata' from origin 'http://localhost:50362' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Before sending the GET request to server, browser automatically send and preflight OPTIONS request, and your server doesn't allow this method. You need to enable OPTIONS method support in your server side (219.90.67.163)
Are you use Bearer Token Authentication?
requst headers try this
headers: {
"Authorization": "Bearer QXBpVXNlcjpBcGlQYXNz",
},
You must setting CORS in Web API
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
The CORS plugin you are using only works for Simple Requests.
Since you are setting an Authorization header you are making a Preflighted Request which your plugin cannot handle.
You need a different approach to handling the Same Origin Policy. Ideally, that would be proper support for CORS on the server you are making the HTTP request to but some other options are listed at the end of this answer.

CORS Error:Response to preflight request doesn't pass access control check when trying to access Azure Search Api

I am using an ajax put request to perform a merge operation to update a field named DocType for a particular document in azure search index. But getting the error: Failed to load resource: the server responded with a status of 404 (Not Found)
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
The ajax request I am performing:
var jsonMeta = {
"value": [
{
"#search.action": "merge",
"metadata_storage_path": "*******jkio********",
"DocType": "Test_Merge"
}
]
};
var jsonString = JSON.stringify(jsonMeta);
var url = "https://documentsmartdetect.search.windows.net/indexes/document-smartdetect-index/docs/index?api-version=2017-11-11";
$.ajax({
url: url,
method: 'PUT',
data: JSON.stringify(jsonMeta),
// This is the important part
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: 'application/json',
headers: {
"api-key": "***************89**",
},
success: function (response) {
},
error: function (xhr, status) {
alert('error');
}
});
I have also tried using Allowed origin type : all on the azure portal. Need some assistance to fix the CORS issue.
Azure Search does not allow calls from front-end JavaScript, so you cannot do what you want directly.
You will have to call Azure Search from a back-end.
This is actually a serious security problem as well since your Search key is now public within the JavaScript that is sent to all visitors of your web app.

AngularJS $http POST turn into GET

I have a route
Route::post('/updateLogo', 'CaptivePortalController#updateLogo');
Then I make a POST here
$http({
method: 'POST', <----- I did a POST
url: '/updateLogo',
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
console.log("data coming into the transform is ", data);
var formData = new FormData();
formData.append("company_logo_path", data.files);
console.log($scope.files.company_logo_path);
return formData;
},
data: { files: $scope.files.company_logo_path }
})
.then(function successCallback(response) {
console.log("success");
console.log(response);
$('.save-fade').delay(500).fadeOut(1000);
}, function errorCallback(response) {
console.log("fail");
console.log(response);
});
When I browse the file, and submit the form, I kept getting
405 in my Network tab on Chrome Dev Tool.
Then, I click on it, I see
MethodNotAllowedHttpException in RouteCollection.php line 218:
I know that I'm NOT suppose to make a GET to a POST route, but Why does it make a GET request instead of a POST?
Request URL:http://l.ssc.com:8888/en/updateLogo
Request Method:GET <------
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:8888
Referrer Policy:no-referrer-when-downgrade
What did do wrong here ?
Any hints ?
This looks like a re-direction taking place.
refer : $http.post() method is actally sending a GET
Please check your route configuration at the server, make sure it is exactly the same as you're requesting.
If you're requesting a '/myroute' but you've defined the route as '/myroute/' then your server could be redirecting to '/myroute'.
All re-directions are done using a GET.
And since the route doesn't allow GET request, it's returning a 405.

Ajax call to Mailchimp API 3.0 returns HTTP 501

I am trying to simply subscribe a mail address with the name to a MailChimp list.
I thought this should be very easy but I can't manage to post the mail address there.
You can find the full code here (key=authkey):
$(document).ready(function(){
$('#blogsignup').submit(function(event){
event.preventDefault();
$.ajax({
url : "https://us12.api.mailchimp.com/3.0/lists/247e2f0702/members/",
dataType : "json",
headers: { "Content-Type":"application/json", 'Access-Control-Allow-Origin': '*', "Accept": "application/json", "Authorization": "key-us12" },
type : 'POST',
contentType: "application/json",
data : {
apikey: "key",
email_address: $('#TBemail').val(),
status: 'subscribed',
merge_fields: {
FNAME: "subscriberFirstName",
LNAME: "subscriberLastName"
}
},
// Try to send also before
beforeSend: function(xhr) { xhr.setRequestHeader("Authorization",
"Basic " + btoa("api:" + "key-us12"));
},
success : function (data) {
$('#signup').html("Thanks for signing up. We will contact you as fast as possible.");
},
error : function (data, errorThrown) {
alert(errorThrown);
console.log(data);
}
});
});
});
The function is triggered when clicking the submit button.
I always get the alert "error" and it's saying
XMLHttpRequest cannot load https://us12.api.mailchimp.com/3.0/lists/247e2f0702/members/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://preprod.travelgap.io' is therefore not allowed access.
The response had HTTP status code 501.
I was also trying jsonp as Datatype then I get a 401 error. Authkey not passed.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This means that the client (making the AJAX call) is not permitted to directly hit the API. Your current architecture:
Client (any origin) ---> MailChimp API
What you should do, as suggested already, is use your server to proxy over the request to the remote API, so that you don't violate their CORS rule. You should add an API endpoint on your server which, when accessed by a client, makes a server-side network request to the MailChimp API.
Client (any origin) ---> Server (known, whitelisted origin) ---> MailChimp API
Also, your API key should never exist in client code. Your API key should be considered a secret available only server-side. The latter architecture ensures that this is the case.

CORS issue while submitting data to google forms in angular

While submitting the data :
Error Message : XMLHttpRequest cannot load https://docs.google.com/forms/d/xxxxxxxxxxxxx/formResponse. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8090' is therefore not allowed access. The response had HTTP status code 405.
$scope.postDataToGoogle = function(){
$http({
method: 'POST',
crossDomain: true,
url: 'https://docs.google.com/forms/d/XXXXXXXXXXXXXXXXXXXXXXXX/formResponse',
// dataType: "xml",
data: tempData,
}).success(function(data,status){
//alert(data)
console.log("Success");
}).error(function(data,status) {
console.log('Error:' + status);
});
}
Its not about jquery or angular, CORS allows or disallow done by Back-end server.
Google might not support this.(to access https://docs.google.com)
CORS (Cross-Domain Resource Sharing) allows you to more cleanly separate your front-end from your back-end.
CORS is a group of special response headers sent from the server that tell a browser whether or not to allow the request to go through
Access-Control-Allow-Origin: http://example.com.
Why does jQuery throw an error when I request external resources using an Appcache Manifest?
I do have tried with angular still not able solve it, but with jQuery its works for me.
$.ajax({
url: 'https://docs.google.com/forms/d/xxxxxxxxx',
data: tempData,
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
alert('error');
},
200: function () {
alert('Thank you for your valuable feedback');
}
}
})

Categories

Resources