I'm posting this on my way home, so forgive the lack of code but I'll try to be as detailed as possible and add code when I can tonight. So essentially I have a react native app using redux and axios. A brief review (code to follow) may explain that I'm doing something wrong.
Serviceapi.js
Creates and exports basic axios with base url.
const ServiceApi = axios.create({
baseURL: BASE_URL,
responseType: 'json'
});
AuthReducer.js
On login sets Authorization header manually using the post method. This works on both android and ios the login is returned and I use the authorization header.
return {
type: PERFORM_LOGIN,
payload: {
user: {
name: username
},
request: {
url: '/login',
method: 'post',
headers: {
'Authorization': 'Basic ' + basicAuth
}
}
}
On login, I return the following redux-axios action, you can see that I set the header: Authorization manually, this works great.
// On login success, set the authInterceptor responsible for adding headers
authInterceptor = ServiceApi.interceptors.request.use((config) => {
console.log(`Attaching Authorization to header ${basicAuth}`);
config.headers.common.Authorization = basicAuth;
return config;
}, (error) => {
Promise.reject(error);
});
On logout I clear the interceptor. I chose to add and remove on login and logout instead of always having it there just because. This could be a problem but it was fine for Android
// Clear the auth interceptor
ServiceApi.interceptors.request.eject(authInterceptor);
Again this is all working great on Android. And it looks to be working on ios. When I debug the interceptor it's getting called and setting the header.
But I get back a 403 on ios. After looking at the request in more detail, there is a big difference between the android header in the request and the ios header in the request. The rest of the request object is the same, only the _header object is different between ios and android.
Android Request
_headers:
accept: "application/json, text/plain, */*"
authorization: "Basic <correct base64 value>"
content-type: "application/json;charset=utf-8"
__proto__: Object
IOS Request
_headers:
accept: (...)
authorization: (...)
content-type: (...)
get accept: ƒ ()
set accept: ƒ ()
get authorization: ƒ ()
set authorization: ƒ ()
get content-type: ƒ ()
set content-type: ƒ ()
__proto__: Object
With the differences, setting a breakpoint at looking at the console for error.request._headers.authorization; I get the same "Basic: " contents as the Android header contains.
index.php
The backend service is a php file that does a $_SERVER['PHP_AUTH_USER'] which fails a 403 if not set which is what's happening. I don't have access to the php, I was just told this is what it's using.
Again I apologize for not providing code but i will when I get a chance later. Is there something maybe I have to set extra for ios? Or maybe php for ios needs an extra header?
Code to follow.
EDIT Updated with code, hopefully I didn't leave in any of the encoded login info.
EDIT 2 Upon further investigation this looks like it's related to apache/PHP rather than react-native/axios. I threw together an express server that simulated the same checking that the PHP does:
- Look for the Authorization header
- Print it
- Return back 403 or 200 w/ data based on that
When running pointing at http://localhost:3000 using the exact same app on the emulator I get back what I'm expecting. To add to this, when I'm on the emulator, I can't actually login to the live URL (even though I could on the regular device), I get the same 403 error but this time a little earlier.
EDIT 3
To provide some more information from the server, here are the three requests that I've been able to log:
1) This is from the IOS Emulator iPhone8 against a an express server:
accept:"application/json, text/plain, */*"
accept-encoding:"gzip, deflate"
accept-language:"en-us"
authorization:"Basic <base 64 encoding>"
connection:"keep-alive"
content-length:"0"
host:"localhost:3000"
user-agent:"MobileApp/1 CFNetwork/978.0.7 Darwin/18.5.
2) This is from the same emulator to apache/PHP (5.3.3), we can see there is no Authorization header.
Accept: application/json, text/plain, */*
User-Agent: MobileApp/1 CFNetwork/978.0.7 Darwin/18.5.0
Accept-Language: en-us
Accept-Encoding: br, gzip, deflate
Connection: keep-alive
3) This is from Android to apache/PHP (5.3.3):
authorization: Basic <Base 64 encoding>
Host: api.serviceurl.com
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.12.1
Edit 4
So after playing around and googling for some time, it turns out that the issue is with Zend Framework and fastcgi which automatically removes the Authorization header. The weird thing is that it's only doing it from IOS and not from Android, which makes no sense really.
On thing we noticed in the logs, is that it's accepting the Android and Postman as POST but it's logging the IOS requests as GET. I'm not entirely sure what's up with that, but it seems to be another difference. I've updated the task to have zend as a tag. There are a number of SO articles on resolving this with ReWriteMod on apache/zend so I'll give those a go first and see if it fixes the issue.
** Edit 5**
So far we've attempted to follow the SO articles which ask that that that following be added (Authorization header missing in django rest_framework, is apache to blame?):
SetEnvIfNoCase Authorization ^(.*) -e=PHP_HTTP_AUTH
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
which results in the following:
// IOS
_SERVER[PHP_HTTP_AUTH] = <blank>
_SERVER[HTTP_AUTHORIZATION] = <blank>
// Android
_SERVER[PHP_HTTP_AUTH] = Username
_SERVER[HTTP_AUTHORIZATION] = Basic <Base65 encoded>
_SERVER[PHP_HTTP_PW] = Password
So we know that Header Authorization is getting to Apache, but now it's coming through as blank. There are a few other SO answers I'm researching but the search continues...
Edit 6
Resolved(ish)
Turns out it was a trailing slash required on the request for IOS. I was able to find this link https://github.com/square/retrofit/issues/1037 where the the issue was described as:
For those interested: We are using Django as our backend and by default when you do
not provide a trailing slash on the endpoint Django redirects from the non-slash
endpoint to the slash endpoint.
Now, we aren't using Django, but apparently for our configuration of Zend it was
the same issue - Android was able to re-direct without issue, while IOS was not. Another comment on the task states:
OkHttp strips the "Authorization" header when redirected across hosts (connections)
via a 3xx response from the original host.
Which doesn't seem accurate, since Android was using OkHttp and was working fine. It looked like IOS using Darwin had the issue.
EDIT
I forgot something else from my original post, I also had to change my interceptor from the line config.headers.common.Authorization = ... to config.headers.Authorization = ... which for some reason kept the casing. Original way converted Authorization to authorization, while the latter kept it as Authorization. Not sure if this was an issue, but I made it anyhow.
// On login success, set the authInterceptor responsible for adding headers
authInterceptor = ServiceApi.interceptors.request.use((config) => {
console.log(`Attaching Authorization to header ${basicAuth}`);
config.headers.Authorization = basicAuth;
return config;
}, (error) => {
Promise.reject(error);
});
I cannot believe I spent 5 hours debugging and researching to resolve the issue eventually with a trailing slash! Even when I tried the trailing slash I thought it was a futile attempt but it actually resolved my issue. #kendavidson you're a lifesaver!!
Related
I am using the ZenDesk API (https://developer.zendesk.com/rest_api/docs/core/introduction) to synchronise a ZenDesk setup with another client database. When I try to delete an organization, I get a response that seems to suggest an update call has been made.
According to the documentation (https://developer.zendesk.com/rest_api/docs/core/organizations#delete-organization) the call should be DELETE /api/v2/organizations/{id}.json where the {id} is the id of the organization.
I have written code that I believe to be correct, and checked this with Fiddler. The call comes through on Fiddler as:
DELETE /api/v2/organizations/39005971.json HTTP/1.1
The raw request view shows (with redactions):
DELETE https://<redacted>.zendesk.com/api/v2/organizations/39005971.json HTTP/1.1
Authorization: Basic <redacted>
Host: <redacted>.zendesk.com
Accept: */*
Content-Type: application/json
and the response comes back as:
{
"error":"RecordInvalid",
"description":"Record validation errors",
"details":{
"name":[
{
"description":"Name: has already been taken",
"error":"DuplicateValue"
}
]
}
}
This is the same response that is given if you try to insert an organization with the same name as an existing one. From the documentation, the basic difference between deleting and updating a record is that delete requests use DELETE and updates use PUT - the endpoint URL is the same.
Does anyone have any suggestions? I can provide upstream code (in PHP) if needed, however as Fiddler is picking up the request as a correctly formatted DELETE, I'm not sure that the code is going to help.
I actually work for Zendesk and figured this out personally. You seemed to have run into a bug having to do with the max characters an organization name can have. You probably had a couple organizations whose names were more than 255 characters long and after getting truncated to 255 were the same name. Now validation issues are popping up. I'm really sorry about that!
I would send a request to https://support.zendesk.com/hc/en-us/requests/new and we'll fix this issue for you!
So I was writing an app when I got across this issue.
This is the PHP : Slimframework Corresponding :
$app->delete('/products/:id',function($id) use($app){
$db = new mysqli('notsocoolhost','verycooluser','verycoolpassword','verycooldatabase');
$db->query("DELETE from products WHERE id='$id'");
});
I removed the part where I confirm that you can actually delete it from the database.
This is Angular.JS :
$scope.del = function(product){
$http({
method: "DELETE",
url: baseUrl + product.id
}).success(function(){ ...... //Returns 0 -> WTF?
This buddy here returns in error status : 0
and this one below returns 405:
$scope.delete(baseUrl + product.id).success ... //Returns 405 : Method Not Allowed
To sum it up, I added couple of tests on Hurl.it and the RESTApi from Slimframework is fully functioning. which leaves it as Angular.js problem ? I guess?
UPDATE:
After further inspection I've revealed the following:
1) Mysteriously the : Request Method (Field by Firefox) is OPTIONS.
2) Access-Control-Request-Method : "DELETE"
3) Access-Control-Allow-Methods: "GET,POST,DELETE,PUT"
I hope this serves people in the future.
Back to basics, having trouble sending $http requests in cross-origin requests has nothing to do with the server nor Angular.js.
If you are like me hosting your webapp on:
https:\\www.beautifuldomain.com
and your API on :
https:\\api.beautifuldomain.com
Whenever you try to perform a request between Webapp and API you are performing Cross-Origin Request.
What does it mean?
It means that your message will be considered as Cross-Origin and it will be preflighted.
Preflighted?
It means that when you use any method other than GET,HEAD or POST.
Also POST if used to send request data with Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g.
It will be sent as method: OPTIONS. -- That is preflighted.
OK, OK I understand, but what do i do?
Now that is clear we have two options to move on:
First Option:
Leaving the web-server structure as is i.e:
www.example.com -> Angular Web-App
api.example.com -> API - subdomain
FOR POST:
And add a transformRequest setting to $httpProvider like so:
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
(Remember preflighted, well it does allow us to send x-www-form-urlencoded.)
What is left from there is make sure you set your data in x-www-form-urlencoded format looks like so :
name=Andy&nickname=RainbowWarrior&....
FOR DELETE:
This one is a bit more complicated since you have to do some server side tweak.
If you are using Slimframework for PHP like I do, all you got to do is:
$response = $app->response();
$response->header('Access-Control-Allow-Origin', '*');
$app->options('/path/to/resource',function(){}); // This one just so you can accept OPTIONS it does nothing.
$app->delete('/path/to/resource',function()
{//your delete code is here
});
Now whenever you try to perform DELETE from angular you will see on XHR tab in w/e browser you are using that There is OPTIONS request that was made and right after DELETE.
Second Option:
Much less of a headache .
Move your API into the same domain i.e
www.example.com - Webapp
www.example.com/api - API
And you are protected from all of that above.
This took me 7 hours of research I hope it will help you guys and save you time!.
I'm creating a SublimeText 2 plugin that posts data to a server I run. I wrote the basics while on the train using my phone as a WiFi hot spot and everything worked fine. Then when I got home I got a 400 Bad Request response from my server no matter what I tried to post. I put my laptop back on my personal hot spot and the error went away. Here are the details:
The "client" in this case is Sublime Text 2. If you don't already know, their plugins are written in Python and I'm using urllib, urllib2, and httplib to handle requests. Here is the relevant Python that makes the request:
params = urllib.urlencode({'title': 'ST2 Note', 'content': data, 'user': user, 'pass': pswd})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("staging.myserver.me:80")
conn.request("POST", "staging.myserver.me/st2", params, headers)
response = conn.getresponse()
data2 = response.read()
print data2
conn.close()
The code above sends a POST request just fine. If I'm on a certain connection my server definitely understands it because I set it to just echo back what I send in the POST data. The request is being made to part of a PHP (Codeigniter) application and yes, I've specifically set it up so that CSRF protection is off for this particular URL so I know that's not the issue. The PHP code itself is rather uninteresting but I set it to echo back the server headers and this is what it sent when I made the request from the connection that works:
Host: staging.myserver.me
Accept-Encoding: identity
Content-Length: 56
Content-type: application/x-www-form-urlencoded
Accept: text/plain
Via: HTTP/1.1 akrmspsrvz9ts212.wnsnet.attws.com
Any ideas why the server understands requests from some connections but not others?
Looks like I got it working. I KNOW there are others with my problem out there so here's what happened...
For reasons that I'm too much of a Python/HTTP1.1 newbie to understand, a plan hostname without "http://" in front of it works some of the time. Must have something to do with ISPs and how they route traffic, not sure. So the fix was do modify this line:
conn.request("POST", "staging.myserver.me/st2", params, headers)
The above line caused problems. But changing it to this:
conn.request("POST", "http://staging.myserver.me/st2", params, headers)
Got it to work instantly! I hope this helps someone down the line. 400 errors are almost as mysterious as 500 errors sometimes.
I've been banging my head against this problem for nearly two days now, and I'm hoping someone on this site can help me.
I live in China and have a server (shared hosting) located in Hong Kong. I've set up a PHP Twitter proxy on the server, and I connect to the proxy using Twitter for iPhone (AKA Tweetie). It's worked beautifully for the past year or so.
Twitter for iPhone was updated yesterday and now requires XAuth authorization to connect to twitter.com (previously, it used Basic Auth). Since the update, I haven't been able to authenticate myself using my proxy, in spite of making (what I believe to be) the appropriate changes to my proxy.
Conceptually, this isn't a very difficult problem to crack. In order to authenticate with twitter.com using XAuth, an app must send a POST request to https://api.twitter.com/oauth/access_token. The POST body must be of the form:
x_auth_username=aUserName&x_auth_mode=client_auth&x_auth_password=aPassword
Additionally, the POST request must have an Authorization header in the form:
OAuth oauth_signature_method="HMAC-SHA1", oauth_consumer_key="IQKbtAYlXsomeLGkey0HUA", oauth_nonce="8B265865-3F57-44FF-BCD6-E009EA7D4615", oauth_signature="sbwblaho64blahr934mZQ+23DYQ=", oauth_timestamp="1277356846", oauth_version="1.0"
So, what I've done is used .htaccess to copy the Auth header to a $_REQUEST variable using this code:
RewriteCond %{HTTP:Authorization} ^OAuth.*
RewriteRule (.*) index.php?OAuth=%{HTTP:Authorization} [QSA,L]
My proxy copies the contents of that $_REQUEST variable to an instance variable called $self->oauthHeader. Then, I make add it as a header to my cURL request using the following code:
if (isset($this->oauthHeader)) {
$headers[] = 'Authorization: '.$this->oauthHeader;
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$curl_options[CURLOPT_HTTPHEADER] = $headers;
}
I also add the original request's POST body to the cURL's POST body using:
$curl_options[CURLOPT_POST] = true;
$curl_options[CURLOPT_POSTFIELDS] = #file_get_contents("php://input");
I send the cURL request to Twitter. Everything seems to work correctly, but I inevitably receive a response of "Failed to validate oauth signature and token."
I'm at my wit's end, and I can't for the life of me think what I'm doing wrong. Any help would be much appreciated.
You can use this alternative solution, for jailbroken iOS devices only: http://code.google.com/p/gfwinterceptor/
I have successfully gotten an access_token, so it's not a problem with the 3-legged process.
The problem starts when I try to add a new post/activity using the Buzz API...
Here is my request:
POST /buzz/v1/activities/#me/#self?alt=json HTTP/1.1
Host: www.googleapis.com
Connection: close
Accept-encoding: gzip, deflate
User-Agent: Zend_Http_Client
Content-Type: application/json
Authorization: OAuth
realm="",oauth_consumer_key="example.com",oauth_nonce="ce29b04ce6648fbb92efc8f 08c1c0091",oauth_signature_method="HMAC-
SHA1",oauth_timestamp="1277934794",oauth_version="1.0",oauth_token="1%2FcBz o5ckGvCAm3wLWh1SDH3xQNoW--
yek1NVfUa1Qqns",oauth_signature="CUezSiMbvxyN1BTeb3uROlIx8gA%3D"
Content-Length: 86
{"data":{"object":{"type":"note","content":"posting on Buzz"}}}
Here is the response:
{"error":{"errors":[{"message":"Unknown authorization header","locationType":"header","location":"Authorization"}],"code":401,"message":"Unknown authorization header"}}
And here is my base string (the string that the signature gets generated from):
POST&https%3A%2F%2Fwww.googleapis.com%2Fbuzz%2Fv1%2Factivities%2F%40me
%2F%40self&oauth_consumer_key%3Dexample.com%26oauth_nonce
%3D50acc6b7ac48304ae9301134d6988cdb%26oauth_signature_method%3DHMAC-
SHA1%26oauth_timestamp%3D1278065599%26oauth_token
%3D1%252FcBzo5ckGvCAm3wLWh1SDH3xQNoW--yek1NVfUa1Qqns%26oauth_version
%3D1.0
I've even tried this other base string (with the alt=json added in):
POST&https%3A%2F%2Fwww.googleapis.com%2Fbuzz%2Fv1%2Factivities%2F%40me
%2F%40self%3Falt%3Djson&oauth_consumer_key%3Dexample.com%26oauth_nonce
%3Dee8704244623bbcc860bf77bfcadeacc%26oauth_signature_method%3DHMAC-
SHA1%26oauth_timestamp%3D1278069221%26oauth_token
%3D1%252FcBzo5ckGvCAm3wLWh1SDH3xQNoW--yek1NVfUa1Qqns%26oauth_version
%3D1.0
I have tried pretty much everything to get this working - not sure why it always says 'Unknown authorization header'... the header looks fine when compared to other ones that work.
Any ideas?
which endpoint did you use to authorize request token?
developer's guide:
Important: Part of the OAuth process
requires that you direct the user to
the Google Authorization service to
approve access for your application.
Google Buzz requires that you use a
different Authorization service
endpoint, located at
https://www.google.com/buzz/api/auth/OAuthAuthorizeToken.com/buzz/api/auth/OAuthAuthorizeToken.
You should use GET or POST method (depending what request you use). By default Zend uses header-method.
$client->setMethod(Zend_Http_Client::GET);