Google reCAPTCHA, 405 error and CORS issue - javascript

I am using AngularJS and trying to work with Google's reCAPTCHA,
I am using the "Explicitly render the reCAPTCHA widget" method for displaying the reCAPTCHA on my web page,
HTML code -
<script type="text/javascript">
var onloadCallback = function()
{
grecaptcha.render('loginCapcha', {
'sitekey' : 'someSiteKey',
'callback' : verifyCallback,
'theme':'dark'
});
};
var auth='';
var verifyCallback = function(response)
{
//storing the Google response in a Global js variable auth, to be used in the controller
auth = response;
var scope = angular.element(document.getElementById('loginCapcha')).scope();
scope.auth();
};
</script>
<div id="loginCapcha"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
So far, I am able to achieve the needed functionality of whether the user is a Human or a Bot,
As per my code above, I have a Callback function called 'verifyCallback' in my code,
which is storing the response created by Google, in a global variable called 'auth'.
Now, the final part of reCAPCHA is calling the Google API, with "https://www.google.com/recaptcha/api/siteverify" as the URL and using a POST method,And passing it the Secret Key and the Response created by Google, which I've done in the code below.
My Controller -
_myApp.controller('loginController',['$rootScope','$scope','$http',
function($rootScope,$scope,$http){
var verified = '';
$scope.auth = function()
{
//Secret key provided by Google
secret = "someSecretKey";
/*calling the Google API, passing it the Secretkey and Response,
to the specified URL, using POST method*/
var verificationReq = {
method: 'POST',
url: 'https://www.google.com/recaptcha/api/siteverify',
headers: {
'Access-Control-Allow-Origin':'*'
},
params:{
secret: secret,
response: auth
}
}
$http(verificationReq).then(function(response)
{
if(response.data.success==true)
{
console.log("Not a Bot");
verified = true;
}
else
{
console.log("Bot or some problem");
}
}, function() {
// do on response failure
});
}
So, the Problem I am actually facing is that I am unable to hit the Google's URL, Following is the screenshot of the request I am sending and the error.
Request made -
Error Response -
As far as I understand it is related to CORS and Preflight request.So what am I doing wrong? How do I fix this problem?

As stated in google's docs https://developers.google.com/recaptcha/docs/verify
This page explains how to verify a user's response to a reCAPTCHA challenge from your application's backend.
Verification is initiated from the server, not the client.
This is an extra security step for the server to ensure requests coming from clients are legitimate. Otherwise a client could fake a response and the server would be blindly trusting that the client is a verified human.

If you get a cors error when trying to sign in with recaptcha, it could be that your backend server deployment is down.

Related

How to use Google Identity Services JS SDK for authorization?

I'm trying to implement the authorization through google Auth and Javascript SDK following the example given by google documentation:
<!DOCTYPE html>
<html>
<head>
<script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
</head>
<body>
<script>
var client;
function initClient() {
client = google.accounts.oauth2.initCodeClient({
client_id: 'YOUR_CLIENT_ID',
scope: 'https://www.googleapis.com/auth/calendar.readonly',
ux_mode: 'popup',
callback: (response) => {
var code_receiver_uri = 'YOUR_AUTHORIZATION_CODE_ENDPOINT_URI',
// Send auth code to your backend platform
const xhr = new XMLHttpRequest();
xhr.open('POST', code_receiver_uri, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('code=' + code);
// After receipt, the code is exchanged for an access token and
// refresh token, and the platform then updates this web app
// running in user's browser with the requested calendar info.
},
});
}
function getAuthCode() {
// Request authorization code and obtain user consent
client.requestCode();
}
</script>
<button onclick="getAuthCode();">Load Your Calendar</button>
</body>
</html>
However there are two things I don't get in this example:
What is the AUTHORIZATION_CODE_ENDPOINT_URI
What is the variable named 'code' sent in the callback function ? It is not assigned anywhere in this snippet
Initializing the client works fine, I get the pop up window with the required scope however I can not figure out how to make the second part work and it seems to be fairly new, so not much information about this is available.
YOUR_AUTHORIZATION_CODE_ENDPOINT_URI is where your identity is verified and where code is being sent to. See here for more information on Authorization Endpoint.
As for code. It's not this:
xhr.send('code=' + code);
It's this:
xhr.send('code=' + response.code);
We receive code as a response. That's how we get the value. See this line here.
callback: (response)
code is a part of the Google OAuth 2.0 process. It refers to the Authorization Code that Google sends you once you have verified your identity. Once you have received your code you can exchange it for a token that can be used to access Google APIs.
Any time the token expires, the application using has to request a new one via the access code. This provides a degree of separation from you and your passwords to the Google APIs.
See here for more info on Authorization codes.
See here for more info on Google using OAuth2.
See diagram below to see the full process.
Hope that helps.

Angular Cross-Origin Request CORS failure, but node http.get() returns successfully

I am trying to access an API using AngularJS. I have checked the API functionality with the following node code. This rules out that the fault lies with
var http = require("http");
url = 'http://www.asterank.com/api/kepler?query={"PER":{"$lt":1.02595675,"$gt":0.67125}}&limit=10';
var request = http.get(url, function (response) {
var buffer = ""
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
console.log(buffer);
console.log("\n");
});
});
I run my angular app with node http-server, with the following arguments
"start": "http-server --cors -a localhost -p 8000 -c-1"
And my angular controller looks as follows
app.controller('Request', function($scope, $http){
// functional URL = http://www.w3schools.com/website/Customers_JSON.php
$scope.test = "functional";
$scope.get = function(){
$http.get('http://www.asterank.com/api/kepler?query={"PER":{"$lt":1.02595675,"$gt":0.67125}}&limit=10',{
params: {
headers: {
//'Access-Control-Allow-Origin': '*'
'Access-Control-Request-Headers' : 'access-control-allow-origin'
}
}
})
.success(function(result) {
console.log("Success", result);
$scope.result = result;
}).error(function() {
console.log("error");
});
// the above is sending a GET request rather than an OPTIONS request
};
});
The controller can parse the w3schools URL, but it consistently returns the CORS error when passed the asterank URL.
My app avails of other remedies suggested for CORS on this site (below).
Inspecting the GET requests through Firefox shows that the headers are not being added to the GET request. But beyond that I do not know how to remedy this. Help appreciated for someone learning their way through Angular.
I have tried using $http.jsonp(). The GET request executes successfully (over the network) but the angular method returns the .error() function.
var app = angular.module('sliderDemoApp', ['ngSlider', 'ngResource']);
.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
You should understand one simple thing: even though those http modules look somewhat similar, they are totally different beasts in regards to CORS.
Actually, the node.js http.get() has nothing to do with CORS. It's your server that makes a request - in the same way as your browser does when you type this URL in its location bar and command to open it. The user agents are different, yes, but the process in general is the same: a client accesses a page lying on an external server.
Now note the difference with angular's $http.get(): a client opens a page that runs a script, and this script attempts to access a page lying on an external server. In other words, this request runs in the context of another page - lying within its own domain. And unless this domain is allowed by the external server to access it in the client code, it's just not possible - that's the point of CORS, after all.
There are different workarounds: JSONP - which basically means wrapping the response into a function call - is one possible way. But it has the same key point as, well, the other workarounds - it's the external server that should allow this form of communication. Otherwise your request for JSONP is just ignored: server sends back a regular JSON, which causes an error when trying to process it as a function call.
The bottom line: unless the external server's willing to cooperate on that matter, you won't be able to use its data in your client-side application - unless you pass this data via your server (which will act like a proxy).
Asterank now allows cross origin requests to their API. You don't need to worry about these workarounds posted above any more. A simple $http.get(http://www.asterank.com/api/kepler?query={"PER":{"$lt":1.02595675,"$gt":0.67125}}&limit=10')
will work now. No headers required.I emailed them about this issue last week and they responded and configured their server to allow all origin requests.
Exact email response from Asterank : "I just enabled CORS for Asterank (ie Access-Control-Allow-Origin *). Hope this helps!"
I was having a similar issue with CORS yesterday, I worked around it using a form, hopefully this helps.
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
})
.controller('FormCtrl', function ($scope, $http) {
$scope.data = {
q: "test"//,
// z: "xxx"
};
$scope.submitForm = function () {
var filters = $scope.data;
var queryString ='';
for (i in filters){
queryString=queryString + i+"=" + filters[i] + "&";
}
$http.defaults.useXDomain = true;
var getData = {
method: 'GET',
url: 'https://YOUSEARCHDOMAIN/2013-01-01/search?' + queryString,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
console.log("posting data....");
$http(getData).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
});
}
})
<div ng-controller="FormCtrl">
<form ng-submit="submitForm()">
First names: <input type="text" name="form.firstname">
Email Address: <input type="text" ng-model="form.emailaddress">
<button>bmyutton</button>
</form>
</div>
Seems to work with the url you posted above as well..
ObjectA: 0.017DEC: 50.2413KMAG: 10.961KOI: 72.01MSTAR: 1.03PER: 0.8374903RA: 19.04529ROW: 31RPLANET: 1.38RSTAR: 1T0: 64.57439TPLANET: 1903TSTAR: 5627UPER: 0.0000015UT0: 0.00026
I should also add that in chrome you need the CORS plugin. I didn't dig into the issue quite as indepth as I should for angular. I found a base html can get around these CORS restrictions, this is just a work around until I have more time to understand the issue.
After lots of looking around. The best local solution I found for this is the npm module CORS-anywhere. Used it to create AngularJS AWS Cloudsearch Demo.

How to use Azure mobile service REST api?

The new custom API script allows a lot of customization through any type of connection.
I found that this website Custom API in Azure Mobile Services – Client SDKs describes the custom API.
var client = new WindowsAzure.MobileServiceClient('http://myservice.azure-mobile.net/', 'mykey');
client.invokeApi('query', {
method: 'POST'
});
But I couldn't run this code. It is supposed to show a message "Hello post World!".
I put the code inside tags in an HTML file and ran it but nothing happened.
Any help?
The call you have is making a call to your service, but it's ignoring its response. Assuming you have a custom API called 'query' (since it's what you're passing to invokeApi) with the following body:
exports.post = function(request, response) {
response.send(200, { message: 'Hello world' });
};
Your client code is calling it and (if everything goes fine) receiving the response, but it's not doing anything with it. There are a couple of ways to find out whether the call is being made. For example, you can add a log entry in the API and check the logs in your service:
exports.post = function(request, response) {
console.log('The API was called');
response.send(200, { message: 'Hello world' });
};
Or you can use a networking tool (the browser developer tools or Fiddler, for example) to see if the request is being made. Or you can actually do something with the result in the client side:
var client = new WindowsAzure.MobileServiceClient('http://myservice.azure-mobile.net/', 'mykey');
client.invokeApi('query', {
method: 'POST'
}).done(
function(result) { alert('Result: ' + JSON.stringify(result)); },
function(error) { alert('Error: ' + error); }
);
One thing which you need to look at if you're calling the API from a browser is whether the domain from where the page is being loaded is in the 'allow requests from host names' list, under the 'configure' tab, 'cross-origin resource sharing (cors)' section. If it's not, then you may get an error instead of the response you want.

Retrieving Temporary Access Token using jQuery OAUTH

I am attempting to make an API OAUTH2 call to Shopify to authenticate. When I go to my application, the first screen comes up. I press Install, and then it redirects me back to where I started. The problem is that when I get redirected, I cannnot seem to catch it in my jQuery ajax function and therefore I am unable to get the temporary token I need to create my permanent token from OAUTH. The 2nd image shows what is happening after I press install. My code so far is posed below. None of the console.log() functions are being called after I run the ajax call.
My application URL for my app is set to
http://localhost
and my application is running from
http://localhost/shippingcalculator.
I tested the calls in an external REST client program, and I managed to successfully get my access token, so it is not a problem with my credentials.
<!DOCTYPE html>
<script type="text/javascript">
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
console.log(window.location.search);
var results = regex.exec(window.location.search);
if (results == null) return "";
else return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getTemporaryToken(token) {
jso_configure({
"shopify": {
client_id: "67d7af798dd0a42e731af51ffa", //This is your API Key for your App
//redirect_uri: "", OPTIONAL - The URL that the merchant will be sent to once authentication is complete. Must be the same host as the Return URL specified in the application settings
authorization: "https://emard-ratke3131.myshopify.com/admin/oauth/authorize",
//In your case the authorization would be https://SHOP_NAME.myshopify.com/admin/oauth/authorize
scope: ["read_products"], //Set the scope to whatever you want to access from the API. Full list here: http://api.shopify.com/authentication.html
}
});
$.oajax({
url: "https://emard-ratke3131.myshopify.com/admin/oauth/authorize",
jso_provider: "shopify",
jso_scopes: ["read_products"],
jso_allowia: true,
success: function(data) {
//Use data and exchange temporary token for permanent one
if (jqXHR.status === 200) {
console.log("200");
}
if (jqXHR.status === 302) {
console.log("300");
}
console.log("Response (shopify):");
console.log(data);
},
error: function(e) {
console.log("Fail GET Request");
console.log(e);
},
complete: function(xmlHttp) {
// xmlHttp is a XMLHttpRquest object
console.log(xmlHttp.status);
}
});
console.log("Code: " + getParameterByName("code"));
}
}
$(document).ready(function() {
getTemporaryToken();
});
</script>
</head>
<body>
Hello World!
</body>
</html>
It's a pretty bad idea to do all of this client side, your API key will be in the clear for anyone to see and use. On top of that where will you store the token? There are also cross site scripting restrictions built into all browsers that will prevent JavaScript from making calls to sites other than the one the js is loaded from.
You should really do the authentication and make all your API calls from a server.

Should I handle CODE using Javascript SDK FB.login POP-UP or is it handled automatically to gain the access_token?

In the authentication flow documentation here it mentions the CODE which is returned upon oAuth authentication.
Is this required for the Javascript SDK or is this handled automatically in the background in this code?
By "is this required?" I mean, do I have to handle this code to verify the authenticity of the request, or does the JavaScript SDK use the code automatically to gain the access_token.
The documentation explains the client side flow, and how to get the access token using the 'code' so until now. I've been assuming that the SDK manages this automatically in the background, because it produces an access code as response.authResponse.accessToken.
FB.login(function(response) {
if (response.authResponse) {
// User is logged in to Facebook and accepted permissions
// Assign the variables required
var access_token = response.authResponse.accessToken;
var fb_uid = response.authResponse.userID;
alert(dump(response.authResponse));
// Construct data string to pass to create temporary session using PHP
var fbDataString = "uid=" + fb_uid + "&access_token=" + access_token;
// Call doLogin.php to log the user in
$.ajax({
type: "POST",
url: "ajax/doLogin.php",
data: fbDataString,
dataType: "json",
success: function(data) {
// Get JSON response
if (data.result == "failure")
{
alert(data.error_message);
window.location.reload();
return false;
}
else if (data.result == "success")
{
window.location.reload();
return true;
}
},
error: function() {
return false;
}
});
} else {
// user is not logged in and did not accept any permissions
return false;
}
}, {scope:'publish_stream,email'});
I would like to know, because I want to ensure that my code is secure.
From the documentation
With this code in hand, you can proceed to the next step, app authentication, to gain the access token you need to make API calls.
In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint at https://graph.facebook.com/oauth/access_token. The app secret is available from the Developer App and should not be shared with anyone or embedded in any code that you will distribute (you should use the client-side flow for these scenarios).
If you plan on using the FB.api function to make calls to their Graph API, then you need the code to get the access token. But if you only need to authenticate the user, then what you have will do that just fine.

Categories