Can I make an httplib POST request that returns a status of 500 from my Twython callback handler? - twython

In my callback handler from twitter, I cannot seem to make a httplib POST request as it throws an unrelated 401 Token Invalid Expired error. I'm using Google App Engine and have tried the urlfetch function as well.
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection(create_url)
conn.request("POST", "", form_data, headers)
response = conn.getresponse()
if response.status == 500:
# do stuff
Matching error log:
Twitter API returned a 401 (Unauthorized), Invalid / expired To ken

The solution was to use the Requests library for the POST request. For some unknown reason neither httplib or urlfetch work in the twittercallback endpoint on Google App Engine.

Related

Access to XMLHttpRequest at <url> has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers

Im trying to consume TomTom maps api to get the location .
My function :
getLocationAddress(lat: number, lon: number) {
const url = `${baseUrl}search/${versionNumber}/reverseGeocode/${lat},${lon}.json/?key=${apiKey}`;
const headers = new HttpHeaders({
"Content-type": "application/json",
"Access-Control-Allow-Methods": "GET,OPTIONS,POST",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Authorization,Content-Type",
});
const observable = this.http.get(url, { headers: headers });
return observable;
}
The url is correct and i have provided the headers as above . I cant get past this error:
Access to XMLHttpRequest at <url> has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
TomTom is a 3rd party api server . The is routed to the correct location and i can see the response from the server on the browser when pasting the link in a new window
Based on the error message it appears your headers are misconfigured, specifically the "authorization" header attribute.
You may want to use their SDK and/or JS libraries, at it will set the headers for you.
You need to provide an API key, otherwise CORS policy will reject the requests, as shown in their examples https://developer.tomtom.com/maps-sdk-web-js/functional-examples#examples,code,vector-map.html

HTTP authorization headers not send with codeigniter api in ionic 2

In API they call without Authorization is fine.
How to set header for it?
"thanks"
let headers: Headers = new Headers({ 'Authorization': token, 'Content-Type': 'application/json; charset=UTF-8' });`
let options: RequestOptions = new RequestOptions({headers: headers});
let params: URLSearchParams = new URLSearchParams();
params.append('latitude', '23.259933');
params.append('longitude', '77.412615');
params.append('nearby', '5');
return this.http.post(baseUrl, params, options)
.map(
(response: Response)=>{
return response;
}
)
Chrome console:
Response for preflight has invalid HTTP status code 404
This happens because the browser sends the headers of your request to the server before sending the actual request (what is called preflight) so as to verify your request complies with the CORS policy that is defined in the server's configuration.
So what you need to do is double check that the server you are contacting is configured properly to accept the request as you make it.
Make sure that your backend server is accepting not only the POST request but also an OPTIONS request for the same endpoint url. The OPTIONS request should just return with the success 200 code.
On that server you probably have something like "when a user hits endpoint /abc with request type POST, then return some data". You also need something that says "when a user hits endpoint /abc with request type OPTIONS return 200 OK"
If all else fails you could try using this plugin in your browser, but keep in mind this will help only continuing development and is a band-aid solution that won't work in production of course.

Exchanging oauth2 authorization code with access token

In my metro application, I am using google drive apps to get the files from drive.
After I get the code, I am getting error 400 (Invalid request) while exchanging it with access token.
This is my POST request:
https://accounts.google.com/o/oauth2/token?client_id=59349429483.apps.googleusercontent.com&client_secret={DELETED_INTENTIONALLY}&code=4%2FY-rI6ye27Msho3mxmkT7cyDxWzDs&grant_type=authorization_code&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob
The response I am getting is:
Status: 400
Response: {
"error" : "invalid_request"
}
Could anyone please let me know the problem with my request? I am setting the request parameters exactly as per google's documentation.

Error while posting app request in Facebook using app login

I am trying to post an apprequest to a user using the URL:
https://graph.facebook.com/USER_ID/apprequests?message=’This is a new message from the pgm’&data='t1t2t3t4’&access_token=ACCESS_TOKEN_RECEIVED_FROM_FB&method=post
I am getting the following error:
Response Message Bad Request Response Code 400 App Request ID: 400 Bad Request
Method Not Implemented
Invalid method in request
Note: I got the access token and the same url works fine in the browser (Chrome).
Am I missing something? Couldn't find much in the documentation!
Regards
You need to url-encode your parameters. The browser does this transparently to you, that's why it's working there. Assuming you're using php:
http_build_query(array(
"message" => "This is a new message from the pgm",
"data" => "t1t2t3t4",
"access_token" => ACCESS_TOKEN_RECEIVED_FROM_FB,
"method" => "post"
));
This will take care of the encoding and joining parameters via amperstand characters. The return value is:
message=This+is+a+new+message+from+the+pgm&data=t1t2t3t4&access_token=ACCESS_TOKEN_RECEIVED_FROM_FB&method=post

ASP.NET MVC Authorize Attribute does a 302 redirect when the user is not authorized

MSDN explicitly says it should do 401 redirect, but I'm getting a 302 redirect on FF, and this is causing problems in AJAX requests as the returned status is 200 (from the redirected page).
http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx
I've found someone else with the same problem:
http://blog.nvise.com/?p=26
Any other solution, besides his?
I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective.
Global.asax:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 302 &&
Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
Context.Response.Clear();
Context.Response.StatusCode = 401;
}
}
Client Side Code:
$(function () {
$.ajaxSetup({
statusCode: {
401: function () {
location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
}
}
});
});
The Authorize attribute does return a Http 401 Unauthorized response. Unfortunately, however if you have FormsAuthentication enabled, the 401 is intercepted by the FormsAuthenticationModule which then performs a redirect to the login page - which then returns a Http 200 (and the login page) back to your ajax request.
The best alternative is to write your own authorization attribute, and then if you get an unauthenticated request that is also an Ajax request, return a different Http status code - say 403 - which is not caught by the formsAuthenticationModule and you can catch in your Ajax method.
I implemented my own custom authorize attribute which inherited from AuthorizeAttribute and ran into the same problem.
Then I found out that since .Net 4.5 there is a solution to this - you can suppress the redirect in the following way:
context.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
Then the response will be a 401 - Unauthorized, along with the HTTP Basic authentication challenge.
More info here
If you are using a ASP.NET MVC 5 Web Application go to App_Start -> Startup.Auth.cs. Check if app.UseCookieAuthentication is enabled and see if CookieAuthenticationOptions is set to LoginPath = new PathString("/Login"), or similar. If you remove this parameter 401 will stop redirecting.
Description for LoginPath:
The LoginPath property informs the middleware that it should change an
outgoing 401 Unauthorized status code into a 302 redirection onto the
given login path. The current url which generated the 401 is added to
the LoginPath as a query string parameter named by the
ReturnUrlParameter. Once a request to the LoginPath grants a new
SignIn identity, the ReturnUrlParameter value is used to redirect the
browser back to the url which caused the original unauthorized status
code. If the LoginPath is null or empty, the middleware will not look
for 401 Unauthorized status codes, and it will not redirect
automatically when a login occurs.