Error posting photo or video with Instagram Web Api - http-post

When I publish the https://www.instagram.com/media/configure/ I get a forbidden error (403)
i upload the photo ----->
theUrl = "https://www.instagram.com/rupload_igphoto/" + entityName;
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("x-instagram-rupload-params",
media_type: 1,
upload_id: Date.now(),
upload_media_height: _img.height,
upload_media_width: _img.width
}));
xmlhttp.setRequestHeader("Content-Type", "image/jpeg");
xmlhttp.setRequestHeader("X-Entity-Name", entityName);
xmlhttp.setRequestHeader(
'X-Entity-Length', chunkSize,
);
xmlhttp.setRequestHeader(
'Offset', 0,
);
<----- result 200
media configure ----->
theUrl = "https://www.instagram.com/create/configure/";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(
'upload_id=' + _upload_id + '&caption=testing&usertags=&custom_accessibility_caption=&retry_timeout='
)
<----- result eror 403

Try setting the X-CSRFToken in the RequestHeader.
ex:
xmlhttp.setRequestHeader("X-CSRFToken", "your token");
HTTP's 403 Forbidden client error response code is the same as the one the server sends to Indicates that the request was understood, but the authentication was rejected.
This status is similar to the 401, but in this case re-authenticating will not change the result. Access has been permanently banned, such as you lack permission to access the resource. It is tied to the logic of the application.

Related

How to send firebase auth tokens to backend server?

I want to identify currently signed-in user on my nodejs server. To do so securely, after a successful sign-in, I have to send the user's ID token to your server using HTTPS.
As in firebase docs
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
If the token is sent to the backend server using AJAX post request then what should be the URL in xhr request var xhr = new XMLHttpRequest(); xhr.open('POST', url , true); and how to recieve it on nodejs backend server app.js file.
Or there is any other method to do it?
You can add an authorization header in request and parse the header value in your nodejs app.
xhr.setRequestHeader('Authorization', firebaseTokenId);
In your nodejs application you can do:
function abc(req, res) {
authHeader = req.get('authorization');
}

tfs extension Origin 'null' is therefore not allowed access

I encounter a problem when I try to call the Teamcity REST service through a TFS extension.
I configured TeamCity as well:
rest.cors.origins = "http://my.tfsserver"
rest.cors.optionsRequest.allowUnauthorized = true
In the TFS extension, I call the following url:
http: //my.teamcity.server:80/app/rest/latest/projects using "XMLHttpRequest"
const pair :string=this.settings.username+":"+this.settings.password;
const encodedCreds:string = btoa(pair);
const basicAuthValue:string = "Basic "+ encodedCreds;
const apiurl:string="/app/rest/latest/projects";
const completeUrl:string = this.settings.urlTeamCity+apiurl;
const xhr = new XMLHttpRequest();
xhr.open("GET",completeUrl,true);
xhr.setRequestHeader('Authorization', basicAuthValue);
xhr.setRequestHeader("Access-Control-Allow-Origin" ,"http://my.tfsserver");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.onerror=function(){
console.log(xhr.response);
}
xhr.send();
I'm getting the following error in the console:
Failed to load http://my.teamcity.server:80/app/rest/latest/projects:
Response for preflight is invalid (redirect)
In the TeamCity rest log, i have the following two lines:
[2018-10-01 14:12:49,891] DEBUG [p-nio-80-exec-9] -
er.rest.APIController/rest-api - Got CORS request from origin 'null',
but this origin is not allowed. Add the origin to 'rest.cors.origins'
internal property (comma-separated) to trust the applications hosted
on the domain. Current allowed origins are: Enabled CORS Origins:
[http://my.tfsserver]
[2018-10-01 14:12:49,892] DEBUG [p-nio-80-exec-9] -
er.rest.APIController/rest-api - REST API request processing finished
in 1ms, status code: 302, request: OPTIONS
'/app/rest/latest/projects', from client 10.69.152.71:59256, no auth
Based on the last line, i modify my code to:
...
xhr.open("GET",completeUrl,true,this.settings.username,this.settings.password)
xhr.withCredentials=true;
...
but, i'm still getting the same error in both chrome console and team city rest log.
in the chrome console, on the network tab, i can see that "origin" header is null but i don't understand why?
Thanks by adavance for any help :)

Calling rest server from mobile app

Following on from https://lists.hyperledger.org/g/composer/message/91
I have adapted the methodology described by Caroline Church in my IOS app.
Again I can authenticate with google but still get a 401 authorization error when POSTing.
I have added the withCredentials parameter to the http header in my POST request.
does the rest server pass back the token in cookie ? I don't receive anything back from the rest server.
where does the withCredentials get the credentials from ?
COMPOSER_PROVIDERS as follows
COMPOSER_PROVIDERS='{
"google": {
"provider": "google",
"module": "passport-google-oauth2",
"clientID": "93505970627.apps.googleusercontent.com",
"clientSecret": "",
"authPath": "/auth/google",
"callbackURL": "/auth/google/callback",
"scope": "https://www.googleapis.com/auth/plus.login",
"successRedirect": "myAuth://",
"failureRedirect": "/"
}
}'
the successRedirect points back to my App. After successfully authenticating I return to the App.
Got this working now. The App first authenticates with google then exchanges the authorization code with the rest server.
The Rest server COMPOSER_PROVIDERS needs to be changed to relate back to the app.
clientID is the apps ID in google,
callbackURL and successRedirect are reversed_clientID://
The App calls http://localhost:3000/auth/google/callback with the authorization code as a parameter.
this call will fail, but an access_token cookie is written back containing the access token required for the rest server.
The user id of the logged in user is not passed back, when exchanging the code for a token with google we get back a JWT with the details of the logged in user. We need this back from the rest server as well as the token. Is there any way to get this ?
changing the COMPOSER_PROVIDERS means that the explorer interface to the Rest server no longer works.
func getRestToken(code: String) {
let tokenURL = "http://localhost:3000/auth/google/callback?code=" + code
let url = URL(string:tokenURL);
var request = URLRequest(url: url!);
request.httpMethod = "GET";
request.setValue("localhost:3000", forHTTPHeaderField: "Host");
request.setValue("text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8", forHTTPHeaderField: "Accept");
request.setValue("1", forHTTPHeaderField: "Upgrade-Insecure-Requests");
request.httpShouldHandleCookies = true;
request.httpShouldUsePipelining = true;
let session = URLSession.init(configuration: .default);
session.configuration.httpCookieAcceptPolicy = .always;
session.configuration.httpShouldSetCookies=true;
session.configuration.httpCookieStorage = HTTPCookieStorage.shared;
let task = session.dataTask(with: request) { (data, response, error) in
var authCookie: HTTPCookie? = nil;
let sharedCookieStorage = HTTPCookieStorage.shared.cookies;
// test for access_token
for cookie in sharedCookieStorage! {
if cookie.name == "access_token"
{
print(“Received access token”)
}
}
guard error == nil else {
print("HTTP request failed \(error?.localizedDescription ?? "ERROR")")
return
}
guard let response = response as? HTTPURLResponse else {
print("Non-HTTP response")
return
}
guard let data = data else {
print("HTTP response data is empty")
return
}
if response.statusCode != 200 {
// server replied with an error
let responseText: String? = String(data: data, encoding: String.Encoding.utf8)
if response.statusCode == 401 {
// "401 Unauthorized" generally indicates there is an issue with the authorization
print("Error 401");
} else {
print("HTTP: \(response.statusCode), Response: \(responseText ?? "RESPONSE_TEXT")")
}
return
}
}
task.resume()
}
have you authorised the redirect URI in your Google OAUTH2 configuration ?
This determines where the API server redirects the user, after the user completes the authorization flow. The value must exactly match one of the redirect_uri values listed for your project in the API Console. Note that the http or https scheme, case, and trailing slash ('/') must all match.
This is an example of an Angular 5 successfully using it Angular 5, httpclient ignores set cookie in post in particular the answer at the bottom
Scope controls the set of resources and operations that an access token permits. During the access-token request, your application sends one or more values in the scope parameter.
see https://developers.google.com/identity/protocols/OAuth2
The withCredentials option is set, in order to create a cookie, to pass the authentication token, to the REST server.
Finally this resource may help you https://hackernoon.com/adding-oauth2-to-mobile-android-and-ios-clients-using-the-appauth-sdk-f8562f90ecff

The HTTP request must contain a user-specific secret - Error in fortify

I have below code in my applicaton.
makeAjaxRequest: function(url, data){
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
var response = Ext.JSON.decode(xhr.responseText);
if (response) {
Ext.Msg.alert('Alert', response.message);
Ext.getBody().unmask();
}
};
Ext.getBody().mask('Loading...');
xhr.send(data);
}
Fortify is showing this error for this line
Error - "The http request at * line * must contain a user-specific secret in order to prevent an attacker from making unauthorized requests"
xhr.open('POST', url, true);
How do i resolve this fortify issue?
Is it something Fortify is highlighting because it doesn't have full context of the application.
In my application i have SSO setup which is passing a user specific secret with every request. But fortify may not be aware of it and ends up flagging this as an issue.
Kindly advice on what is best way to resolve this issue.
Thanks.
You need to add the setRequestHeader !!!
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(data);

ajax from Chrome-Extension processed, but receive responseText="" and status=0

I am writing a google-chrome extension, that needs to make ajax requests to a server, send some data, and receive some data back. My server is Tomcat 6.0, running on localhost.
I am able to receive all the data on the server side, do all the processing I need, and send a response back to the extension,
but the status i get in the callback is 0, and responseText="".
my guess is that the problem lies either in the server - returning a response to a request originating from chrome-extension://... url, or in the extension - receiving a response from localhost:8080.
I've set the necessary permissions of course, and I tried setting content-type of the response to "text/xml", "text/html" and "text/plain" - it makes no difference.
I've tried using ajax both with XMLHttpRequest and JQuery - same problem with both.
I've found these issues, but they don't seem to solve my problem:
1. http://www.plee.me/blog/2009/08/ajax-with-chrome-empty-responsetext/
2. http://bugs.jquery.com/ticket/7653
here's my code:
bg.js (background page)
function saveText(data) {
var requrl = serverUrl + addTextUrl;
var params = json2urlParams(data);
jQuery.ajax({
type : "POST",
url : requrl,
data : params,
success : function (data, textStatus, XMLHttpRequest) {
console.log("Data Saved: " + msg);
}
});
// var xhr = new XMLHttpRequest();
// xhr.open("POST", requrl, true);
// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// xhr.onreadystatechange = function (progress) {
// if (xhr.readyState == 4) {
// console.log("Data Saved: " + this.response);
// }
// };
// xhr.send(params);
}
addContentServlet.java: (server side)
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ErrorCodes error = addContent(request, response);
response.setContentType("text/plain");
//response.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
//response.setIntHeader("errorCode", error.ordinal());
response.getWriter().write(error.toString());
response.setIntHeader("errorcode", error.ordinal());
if(error == ErrorCodes.SUCCESS){
response.setStatus(error.toHttpErrorCode());
response.flushBuffer();
}
else{
response.sendError(error.toHttpErrorCode(), error.toString());
}
}
EDIT:
I've noticed in the chrome console of the background page that for every ajax that returns to the extension i get a
XMLHttpRequest cannot load
http:// localhost:8080/stp_poc/MyServlet.
Origin
chrome-extension://fmmolofppekcdickmdcjflhkbmpdomba
is not allowed by
Access-Control-Allow-Origin.
I tried loosing bg.js and puting all the code in the main page instead - to no avail.
how come XMLHttpRequest agrees to send the request, but not receive it back??
Maybe a server-configuration problem? I'm a newb, so maybe i missed something basic, like a header in the response
EDIT
I've finally pinned the problem:
I shouldn't have included the port number in my permission. Here's the wrong permission I wrote:
"permissions" : [
"http://localhost:8080/"
]
And here's the correct form:
"permissions" : [
"http://localhost/"
]
everything seems to works fine now.
The problem was that I shouldn't have included the port number in my permission.
Here's the wrong permission I wrote:
"permissions" : [
"http://localhost:8080/"
]
And here's the correct form:
"permissions" : [
"http://localhost/"
]

Resources