socket.http headers in lua - lua

I am using the socket.http module to send http request but I am unable to get all the response headers from the http request.
Below is the sample code am using
I need to print all the response headers
Connection close, TE
Content-Length 210
Content-Type application/x-www-form-urlencoded
Host XXXX
TE trailers
User-Agent LuaSocket 3.0-rc1
method POST
protocol HTTP/1.1
test.lua
http = require("socket.http")
header = { }
local result,b,c,h = http.request{ url = "myurl", headers = header,method="POST" }
for k,v in pairs(c) do print(k,v) end
This is the output am getting:
content-type text/html; charset=UTF-8
server Apache/2.2.15 (CentOS)
date Tue, 16 Jun 2015 13:32:50 GMT
connection close
content-length 348
x-powered-by PHP/5.4.35
But I need all the headers like
Connection close, TE
Content-Length 210
Content-Type application/x-www-form-urlencoded
Host XXXX
TE trailers
User-Agent LuaSocket 3.0-rc1
method POST
protocol HTTP/1.1

You do print all response headers.
You can verify it by inspecting the information in the browser's development tools or by inspecting the TCP traffic directly.
By the way, you cannot expect request fields (e.g. user-agent) to be present in the response header.

Related

HTTP/1.1 401 Unauthorized Asana API

PROBLEM: I cannot authorize my connection to ASANA.
Breaking my code to the simplist bits. I used: http://onlinecurl.com/ to mimic what I see at
https://asana.com/developers/documentation/getting-started/authentication#sts=API%20Keys
This is my command.
curl --user 'NWE2MDJqUloubnpCUjh0d3gxVmYydW5BeFlJUER0Smw6' https://app.asana.com/api/1.0/users/me
Original : 5a602jRZ.nzBR8twx1Vf2unAxYIPDtJl
I even used https://www.base64encode.org/ to make sure my base64 was correct, which it is.
Response Header
1 HTTP/1.1 401 Unauthorized
2 Server: nginx
3 Date: Sat, 25 Oct 2014 17:58:23 GMT
4 Content-Type: application/json; charset=UTF-8
5 Transfer-Encoding: chunked
6 Connection: keep-alive
7 X-Asana-Content-String-Length: 41
8 Pragma: no-cache
9 Set-Cookie: TooBusyRedirectCount=0
10 Cache-Control: no-store
11 X-Asana-Preferred-Release-Revision: 20141024_201328_7ebcb21240775f3d5e6038b42ade419530485b76
12 X-Robots-Tag: none
Response Body
1{"errors":[{"message":"Not Authorized"}]}
How can I connect to the service with my Authorization???
Since writing this I have reset my aPIKEY
You do not need to base64-encode the username yourself, curl will do that for you. Also, please be careful of sharing your API key on public forums; these are sensitive credentials that should be treated like usernames and passwords! If that is a real API key I advise you reset it immediately (which you can do through the UI where you discovered it).
There needs to be a content Header
Here is what I did in Google Scripts.
In the site : http://onlinecurl.com/
we would need an extra option in headers for content-type
function getTasksFromAsana() {
api_key = "XXXX";
workspace_id = "WORKSPACE-ID";
// set up HTTPS connection
uri = "https://app.asana.com/api/1.0/users/me";
// set up the request
req={};
req = {
"headers":{ 'content-type': 'application/json','authorization': 'Basic ' + api_key }
}
Logger.log('Get Tasks Asana');
var response = UrlFetchApp.fetch(uri,req);
Logger.log(response.getContentText());
}

Why is action result cached?

I have an action that generates a password reset link and emails it to the user
public ActionResult SendResetPasswordEmail(string userName)
{
var webUser = LoadUser(userName);
if (webUser != null)
{
var token = WebSecurity.GeneratePasswordResetToken(webUser.UserName);
emailSender.SendPasswordResetEmail(webUser, token, resetAction);
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "No user found with username: " + userName);
}
The first time I call the action from the browser, I get an HTTP 200 response (and hit my breakpoint in the action).
The second time I call the action from the browser, I get an HTTP 304 response indicating that the content is unchanged.
There are no [OutputCache] attributes anywhere in the source file (not on the class or the action).
What is causing the web server to decide that the content is unchanged and return the HTTP 304?
I'm aware of a work-around
https://stackoverflow.com/a/18620970/141172
I'm interested in understanding the root cause for the HTTP 304 response.
Update
Headers on first request:
Request Headers
Request GET /Companies/SendResetPasswordEmail/?userName=ej HTTP/1.1
X-Requested-With XMLHttpRequest
Accept */*
Referer http://local:6797/Companies
Accept-Language en-US
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host localhost:6797
DNT 1
Connection Keep-Alive
Cookie __RequestVerificationToken=sNOBS6qz32LtnJpLWgHHELhaE44DfIVE1LSMUgjzHjcwsvxlUFa4lOSyA5QeB8keLXYL08Psjg29CRI7W73uHLJy6A81; .ASPXAUTH=DAF8AF47E955F723EE9438866BE1B4BFBF91BA01912EF087824F03581DBCA05A4AECA01373FAF40DF0C4D5C17F17DEFA2F85C1B702988B7E0F750BFE19566FC711C7D6BD81D8F0B0ABD68AF5B3D9BA032286361F; ASP.NET_SessionId=5e2gcvkc2p3rji25z5emyqzd; HelixPlugins1.0=IEPlugin1.0
Response Headers
Response HTTP/1.1 200 OK
Server ASP.NET Development Server/11.0.0.0
Date Thu, 03 Apr 2014 23:29:02 GMT
Cache-Control private, s-maxage=0
Content-Length 0
Connection Close
NOTE: I changed localhost to local in the above because StackOverflow does not allow links containing localhost to be posted :-)
The browser is Internet Explorer 10.
IE caches ajax responses by default, you need to explicitly tell it not to do any ajax caching by setting your ajax object's cache property to false.
Browsers such as Chrome automatically append a random token to your request to make it unique.

Can Savon allow redirects? 302 "Error"

Is it possible to make Savon allow redirects? I am currently receiving a 302 HTTP Error, but in reality this should just be a redirect instead of an error.
You can setup Savon to follow redirect setting up follow_redirects option to true.
Eg: client = Savon.client(wsdl: url, ssl_verify_mode: :none, follow_redirects: true)
Found here: https://github.com/savonrb/savon/issues/243
Savon uses httpi for the connection. httpi itself is a wrapper around curb, em_http, excon, httpclient, net_http and rack.
The file em_http.rb contains the comment that
automatic redirect following
is not supported by httpi.
So what I would try to send the call to the redirection target right away if that's possible.
To find the "real" URL you can use a tool like curl, for example:
curl -I www.yahoo.in
gives you
HTTP/1.1 301 Moved Permanently
Date: Thu, 18 Aug 2016 18:50:05 GMT
...
Cache-Control: max-age=3600, public
Location: http://in.yahoo.com/
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8
Age: 0
Connection: keep-alive
Server: ATS
The Location: key shows the address you want to try next. You might get another redirect. You'll have to try until the 200 OK is returned.

make HTTP Post request from blackberry java application

In my Blackberry java native application, i am making a call to a dotnet web service whose Request and Response format is defined as below. Here In response XML is being returned. I have been searching the forums and trying for 2-3 days but no success...
Request format :
POST /cinews.asmx/GetSeatLayout HTTP/1.1
Host: webservices.mclients.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
strCinews=string&strTransId1=string&lngSessionId=string&blnScreenOnTop=string&strMergeOption=string&strAreaCats=string
Response format :
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
xml

Box oauth2: Invalid grant_type parameter or parameter missing

I don't know what I do wrong, but everytime I tried to obtain the token (after user authentication of course), the result is always Invalid grant_type parameter or parameter missing
Possibly related to Box API always returns invalid grant_type parameter on obtaining access token
Here is my fiddler result:
POST https://api.box.com/oauth2/token HTTP/1.1
Host: api.box.com
Content-Length: 157
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=nnqtYcoik7cjtHQYyn3Af8uk4LG3rYYh&client_id=[myclientId]&client_secret=[mysecret]
Result:
HTTP/1.1 400 Bad Request
Server: nginx
Date: Thu, 07 Mar 2013 11:18:36 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=5138778bf12a01.27393131; expires=Fri, 07-Mar-2014 11:18:35 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Mon, 06-May-2013 11:18:36 GMT; path=/
Cache-Control: no-store
Content-Length: 99
{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
Even following the curl example gives the same error. Any help would be appreciated.
Edit: tried with additional redirect_uri params but still the same error
POST https://api.box.com/oauth2/token HTTP/1.1
Content-Type: application/json; charset=UTF-8
Host: api.box.com
Content-Length: 187
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=R3JxS7UPm8Gjc0y7YLj9qxifdzBYzLOZ&client_id=*****&client_secret=*****&redirect_uri=http://localhost
Result:
HTTP/1.1 400 Bad Request
Server: nginx
Date: Sat, 09 Mar 2013 00:46:38 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=513a866ec5cfe0.48604831; expires=Sun, 09-Mar-2014 00:46:38 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Wed, 08-May-2013 00:46:38 GMT; path=/
Cache-Control: no-store
Content-Length: 99
{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
Looks like Box requires a correct Content-Type: application/x-www-form-urlencoded request header in addition to properly URL encoding the parameters. The same seems to apply to refresh and revoke requests.
Also, per RFC 6749, the redirect_uri is only
REQUIRED, if the "redirect_uri" parameter was included in the authorization request
as described in Section 4.1.1, and their values MUST be identical.
I was facing a similar issue.
The problem is not with Content-Type.
The issue is with the lifecycle of code you receive.
One key aspect not mentioned in most places is that the code you get on redirect lasts only 30 seconds.
To get the access token and refresh token, you have to make the post request in 30 seconds or less.
If you fail to do that, you get the stated error. I found the info here.
Below code worked for me. Keep in mind, the 30-second rule.
import requests
url = 'https://api.box.com/oauth2/token'
data = [
('grant_type', 'authorization_code'),
('client_id', 'YOUR_CLIENT_ID'),
('client_secret', 'YOUR_CLIENT_SECRET'),
('code', 'XXXXXX'),
]
response = requests.post(url, data=data)
print(response.content)
Hope that helps.
You are missing the redirect URI parameter. Try:
POST https://api.box.com/oauth2/token HTTP/1.1
Host: api.box.com
Content-Length: 157
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=nnqtYcoik7cjtHQYyn3Af8uk4LG3rYYh&client_id=[myclientId]&client_secret=[mysecret]&redirect_uri=[your-redirect-uri]
I have also face same issue implementing oauth2. I have add Content-Type: application/x-www-form-urlencoded. When I add content-type my issue solved.
Check and add valid content-type.
Not sure who might need this in the future but be sure you're sending a POST request to get the access token and not trying to retrieve it by using GET or if you're testing- pasting in the address bar won't work, you need to send a POST request with the data in the BODY and not as query parameter.
Also the code usually lasts for a few seconds, so you need to use it as soon as its sent back.

Resources