Delphi: REST Request with BASIC authentication - rest

I'm using TRESTClient/THTTPBasicAuthenticator/TRESTRequest/TRESTResponse to get data from a server.
With response Ok (200), instead of receiving JSON data, I get as content this:
<script type="text/javascript">
<!-- function redirectToIndex()
{
var adresse = window.location.pathname.split('/');
var httpURL = window.location.hostname + "/" + "app"; // redirect to root
var httpsURL = "https://" + httpURL;
window.location = httpsURL;
}
redirectToIndex(); //-->
This is when TRESTRequest.Accept is empty. If I change for TRESTRequest.Accept:= 'application/json', I get an error
406 - Not Acceptable
Could you tell me what's wrong with my request?

Thank you Peter.
I managed to clarify with the API support the BASIC Authentication using the correct login/password . The documentation was inaccurate.
Access is now working as expected.

Related

How to manage contacts using Contacts API in our website correctly?

I was trying to integrate Google Contacts API to manage the contacts in my website.
I've done the following things:
I've created an application in google developer console and added http://localhost:4200 as URIs & Authorized redirect URIs.
Enabled 'Contacts API'.
I've added the following in my index.html (I've replaced {clientID} with my original client ID (of course):
<script>
function loadAuthClient() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: '{clientID}'
}).then(() => {
console.log("success");
}).catch(err => {
console.log(err);
});
});
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=loadAuthClient" async defer></script>
<meta name="google-signin-client_id" content="{clientID}">
Signed in successfully using:
gapi.auth2.getAuthInstance().signIn().then(() => {
console.log("Logged in")
}).catch(err => {
console.log(err);
});
Tried fetching the contacts using the following:
var user = gapi.auth2.getAuthInstance().currentUser.get();
var idToken = user.getAuthResponse().id_token;
var endpoint = `https://www.google.com/m8/feeds/contacts/`;
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + '?access_token=' + encodeURIComponent(idToken));
xhr.setRequestHeader("Gdata-Version", "3.0");
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.alert(xhr.responseText);
}
};
xhr.send();
But I'm getting the error:
Access to XMLHttpRequest at 'https://www.google.com/m8/feeds/contacts/?access_token={I removed the access token}' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Can someone please guide me where I'm going wrong?
My original response was off the mark. The actual answer is much simpler.
In step 4, try changing your endpoint:
var endpoint = `https://www.google.com/m8/feeds/contacts/default/full`;
In my local tests, this resulted in the expected response.
Another suggestion is to add alt=json to your query, so that you get easy to parse JSON payload. Otherwise you'll get a nasty XML payload in the response.
Here's the updated step 4 with these changes:
var endpoint = `https://www.google.com/m8/feeds/contacts/default/full`;
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + '?access_token=' + encodeURIComponent(idToken) + '&alt=json');
xhr.setRequestHeader("Gdata-Version", "3.0");
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.alert(xhr.responseText);
}
};
xhr.send();
Here's my original response, just in case it helps someone else.
I suspect that you'll need to add http://localhost:4200 to your list of "Authorized JavaScript origins" for the OAuth Client that you are using.
Edit your OAuth 2.0 Client ID and add the URI to the Javascript origins as below:
The other section on that page, Authorized Redirect URIs, only permits the OAuth flow to be redirected back to your web app. Often your web app server will actually consume the APIs so Google doesn't automatically permit CORS access to these APIs to keep things secure.

Setting authorization header in http client in ionic and angular 5

I am learning ionic for mobile development latest version. I used http client for calling REST API. But I am facing some issues -
1) I am using POST but it showing me as option.
2) How to set authorization header . I am using bearer token and my rest API is written in PHP.
Use HttpHeaders to set your token. token can be defined in a string
func() {
var headers = new HttpHeaders();
let body = new HttpParams();
body = body.set('key','value');
headers = headers.set("Authorization", "Bearer " + token)
return this.http.post('post-url.com', body,{
headers:headers
});
}
Hope that helps!

Sending POST data to a page with a GET parameter with Nodejs

I'm trying to send POST data to a test.php file, which handles POST data only if it was provided a specific GET data. Unfortunately I have no clue how to do that; and have been searching for about an hour.
Any help would be appreciated, as i'm currently playing around a lot with this amazing stuff.
Thanks in advance;
Some clarification:
Say you have a index.php looking like this:
<?php
if (isset($_GET['p']))
echo count($_POST) . ' -- ' . count($_GET);
else echo 'fuuu';
?>
<form action="?p" method="POST">
<input type="submit" name="lolw" value="Go" />
</form>
If you submit that form, PHP's $_GET and $_POST superglobals will both contain 1 element.
Now, lets try to run that form through nodeJS.
Here is my test case (which is merely some cutpasting from the doku):
var http = require('http');
var options = {
hostname: 'localhost',
port: 80,
path: '/test.php?lolw=1&p',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
}).on('error', function (e) {
console.log('error in chunk');
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.toString());
});
// write data to request body
req.write('data\n');
req.end();
CLI output gives for the body:
0 -- 2 and then follows the form.
My point is: is it possible to send some parameters through GET and some others through POST, and specifying which needs to be sent through GET and which through POST ?
To make an HTTP request in node.js, you'll need to use http.request. You can set the method to "POST" and still have get parameters in your URL. You'll need to set the Content-Length header to the length of your data and the Content-Type header to application/x-www-form-urlencoded for a "standard" POST request.
Your question is pretty vague. If you're having problems with something in particular, just show your code and ask the more precise question.

Facebook Authentication with JSP

I'm trying to complete Facebook Authentication within a simple JSP page following this example: http://www.sergiy.ca/how-to-implement-facebook-oauth-2.0-app-authorization-process-in-java/
Unfortunately, I'm not very successfull at this point. Your help would be appreciated. As developer of the app, I somehow managed to accept the app and I can see it in my app list. But when I log in as another user, I'm unable to accept the app. The user is not prompted to give access right to the app although the redirect request seems to have been sent to FB. Any help would be much appreciated. My code:
<%# page import="java.util.*,org.apache.commons.codec.binary.*, java.net.*, org.json.simple.*" %>
<html>
<body>
<%
String fbSecretKey = "efqec6fdedd17a64055712dcc7d81f58";
String fbAppId = "116041890091";
String fbCanvasPage = "http://apps.facebook.com/stupidgame/";
String fbCanvasUrl = "http://stupidgame.com:8090/stupidgame/";
String accessToken;
if(request.getParameter("signed_request") != null) {
//it is important to enable url-safe mode for Base64 encoder
Base64 base64 = new Base64(true);
//split request into signature and data
String[] signedRequest = request.getParameter("signed_request").split("\\.", 2);
//parse signature
String sig = new String(base64.decode(signedRequest[0].getBytes("UTF-8")));
//parse data and convert to json object
JSONObject data = (JSONObject)JSONValue.parse(new String(base64.decode(signedRequest[1].getBytes("UTF-8"))));
//check if user authorized the app
if(data.get("user_id")==null || data.get("oauth_token")==null) {
//this is guest, create authorization url that will be passed to javascript
//note that redirect_uri (page the user will be forwarded to after authorization) is set to fbCanvasUrl
response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id=" + fbAppId +
"&redirect_uri=" + fbCanvasUrl + "&scope=publish_stream,offline_access,email");
return;
}
accessToken=data.get("oauth_token")+"";
}else{
response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id=" + fbAppId +
"&redirect_uri=" + URLEncoder.encode(fbCanvasUrl, "UTF-8") +
"&scope=publish_stream,offline_access,email");
return;
}
System.out.println("All set with accessToken:"+accessToken);
%>
</body>
</html>
Since you app is running in an iframe "response.sendRedirect" only redirects the iframe and the auth dialog needs to be the whole page.
Replace:
response.sendRedirect(...)
with:
%><script language="JavaScript"> top.location.href = "<%=auth_url%>"; </script> <%
Or something similar and it should work.
The javascript should be similar to the php docs https://developers.facebook.com/docs/authentication/

MVC + Extjs + IIS6 + Wildcard Mapping = Post Form resulting in 302 object moved

Everything seems to work fine until i want to submit the form and update the database.
Wildcard mapping works on requests like "/navigation/edit/1", but when i submit the form as:
var ajaxPost = function(Url, Params) {
Ext.Ajax.request({
url: Url,
params: Params,
method: 'POST',
async: false,
scope: this
});
};
it says "200 bad response: syntax error" and in firebug there is "Failed to load source for: http://.../Navigation/edit/1".
Any help?
Perhaps its a syntax error: try
params: {"sendparams": Params}
it turns out there was a urlrewrite rule for some other web site corrupting my requests.