I have been trying to use the Stormpath API in my website. I cannot work out how to communicate with the API through PHP. I've tried some variations of cURL but I think I'm missing something...At this stage I'm just trying to make the request from a blank page with known account details - I'm not getting any result.
The API documentation provides this example, for example. What is the simplest way for me to submit the request this using PHP?
Request
POST /oauth/token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: smooth-ensign.apps.stormpath.io
grant_type=password&username=jakub%40stormpath.com&password=Password1%21
Response
{
"access_token": "eyJraWQi[...]0dTpiM",
"refresh_token": "eyJraWQi[...]okvVI",
"token_type": "Bearer",
"expires_in": 3600
}
I also have the Stormpath PHP SDK installed, if that provides a better way to do this.
Related
I'm using currently the Firebase messaging with PHP. I was able to make it work with a single notification with PHP and cURL. I've read the documentation about making batch request and I've constructed the request string as follow:
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
Authorization: Bearer ya29.xxxxxnY
POST /v1/projects/xxxxxxxx/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"token":"cxxxxx3",
"data":{
"typeNoti":"paiement",
"idcompte":"admin",
"typecompte":"paiement"
},
"notification":{
"title":"Test1",
"body":"Notification de test 1"
}
}
}
--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
Authorization: Bearer yaxxxxxxY
POST /v1/projects/xxxxxx/messages:send
Content-Type: application/json
accept: application/json
{
"message":{
"token":"eoxxxxxU1",
"data":{
"typeNoti":"paiement",
"idcompte":"compte2",
"typecompte":"paiement"
},
"notification":{
"title":"Test1",
"body":"Notification de test 1"
}
}
}
--subrequest_boundary--
This string is generated in a file called batch_request.txt as the documentation said. When trying to send the request with cURL I receive this error:
{
"error": {
"code": 400,
"message": "Failed to parse batch request, error: 0 items. Received batch body: (0) bytes redacted",
"status": "INVALID_ARGUMENT"
}
}
I've experienced a strange behavior also, which is when I construct that string manually (in PHP I use HEREDOC), the batch request does occurs with 200ok response. I've tried to find some hidden character but couldn't.
I know there is a library called firebase-php. The problem with it is that I cannot find a straight foreward example like this:
//authenticate with json file
//create new token if it doesn't exist or skip
//create notification array
//create data array
//send multi notifications to multiple devices
I actually use a for loop and mono notification (one device token, one message at a time). The problem with this is that not all notifications are sent.
I appreciate your help thanks!
I gathered the code from firebase-php docs. After installing the library with composer I get a lot of errors and a lot of missing files in Firebase directory inside vendor like Factory.php etc
My solution was to NOT USE firebase-php library due to the numerous bugs I've faced (or maybe misuses) neither to construct the REST request text file for batch request. I used instead the NodeJS SDK which worked like a charm. I'm running a javascript file from my php code using exec.
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!!
I followed this Laravel token API tutorial: http://rjv.im/post/95988160186/api-token-authentication-with-laravel-and-sentry-part. I have written the following cURL request to communicate with my API:
curl -H "X-Auth-Token:tokenhere" http://localhost:8000/account
The request works properly, and accurately returns the expected data. When I translate this to Python I receive urllib2.HTTPError: HTTP Error 401: Unauthorized
import urllib2
req = urllib2.Request('http://localhost:8000/account')
req.add_header("X-Auth-Token", "tokenhere")
resp = urllib2.urlopen(req)
content = resp.read()
print content
If I pass user credentials using basic auth instead of an X-Auth-Token, the request works as expected:
import urllib2
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("http://localhost:8000/account", headers = { "Authorization": basic_authorization("usernameHere", "passwordHere"), })
f = urllib2.urlopen(req)
print f.read()
Any assistance would be much appreciated.
There is something you missed in the tutorial. In the tokens table there is a column:
$table->string('client');
It is important from which client you are sending your request. I am using https://github.com/hisorange/browser-detect to detect from which client I got the request.
But for now I will just try to see User Agent. In my laravel code I just logged every request to see what's happening with the following code:
Route::filter('auth.token', function($route, $request)
{
....
Log::info($request);
....
}
Now, Let's see:
When I use curl from command line:
curl -u user#example.com:password -X GET http://localhost:8000/account
My User Agent is
User-Agent: curl/7.32.0
I sent the same from python using your code above, User Agent is:
User-Agent: Python-urllib/2.7
Ah! That must be it. You have to authenticate your user at least once using Basic Auth, it will give you a token and that token is valid for only that client. In the first part http://rjv.im/post/78940780589/api-token-authentication-with-laravel-and-sentry-part of tutorial there was no such condition. In the comments I received someone posted a query on how to support multiple clients, so this example was made to solve that problem.
Apart from that, may I suggest this library: https://github.com/chrisbjr/api-guard It supports Rate Limiting, easy to integrate with Sentry. It's a bit different from my tutorial. Using my solution you can hit any endpoint using Basic Auth or Token. Using above library, only token is permitted, so there is dedicated route to generate token. Let me know how it goes.
I'm a building a RESTful API using Zend Framework 2 and Apigility by Zend Framework.
For testing, I use the chrome extension Postman REST-Client.
I can do GET requests and POST requests without problems by sending form-data without problems.
But when I try to do a PUT, PATCH or DELETE request, I get the following error:
{
"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
"title":"Unsupported Media Type",
"status":415,
"detail":"Invalid content-type specified"
}
Accept whitelist in Rest-Service-Config of Apigility:
application/vnd.timber-ms.v1+json, application/hal+json, application/json
Content-Type whitelist:
application/vnd.timber-ms.v1+json, application/json
The content-type of the response is application/problem+json
What can I do to fix this and do successfull PUT/PATCH requests?
Is this a problem with Postman or Apigility?
You're getting the 415 error of Unsupported Media Type when Apigility cannot deserialize the data coming from the client. This recently was called out in the documentation.
I suspect your problem is due to the content-type being sent from postman. Pay special attention to the Content-Type Whitelist listed for the service and make sure it contains the content-type you are sending.
For example, if your service has only has application/json in the Content-Type Whitelist and you send the PUT/PATCH with postman as x-www-form-urlencoded, you will get a 415 error of Unsupported Media Type. If you change postman to send the PUT/PATCH with a content-type of application/json and the request body contains valid JSON, Apigility should accept the request.
You can check the content-type postman is sending by clicking on the "Preview" button just to the right of the "Send" button.
I was having a similar issue in Postman with the unsupported media type responses. However, I experienced this response on both PUT and POST requests using my company's API.
I verified that Postman was the problem here and not the request/API in use by running the same request with another similar Chrome extension called Advanced REST Client. I'm not familiar with Apigility, but pretty sure that Postman is the culprit here.
Hoping there is a fix for this issue as Postman and its collections feature is much easier to use than that of Advanced REST Client.
on postman go to normal tab (or other auths tab) and add header:
Content-Type application/json (or any type you need)
make sure that on the raw tab include the json data
{
"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
"title":"Unsupported Media Type",
"status":415,
"detail":"Invalid content-type specified"
}
I had the same problem,
My solution was to write my data to [Body] in the [raw] in json format. Like this:
{"message": "UPDATED First Post!"}
And in [Headers] :
[KEY] Content-Type
[Value] application/json
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);