I upgraded from async_sinatra 0.5.0 to 1.0 because the latter fixed this problem
So far so good. But when I went back to my original app, (as opposed to my test app), which contained authentication, it stopped working. I am using vb.net to make a webrequest, and this worked fine under 0.5.0, but now fails with
"The remote server returned an error: (401) Unauthorized."
Here is my ruby code:
#gem 'async_sinatra', '0.5.0'
require 'sinatra/async'
class AsyncQueryServer < Sinatra::Base
register Sinatra::Async
set :server, 'thin'
set :port, 19876
enable :show_exceptions
helpers do
def protected!
unless authorized?
response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
throw(:halt, [401, "Not authorized\n"])
end
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
begin
puts "@auth.provided? #{@auth.provided?}"
puts "@auth.basic? #{@auth.basic?}"
puts "@auth.credentials #{@auth.credentials}"
rescue Exception => e
puts e.message
end
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['myusername', 'mypassword']
end
end
apost '/execfqy' do
protected!
body request.body.string
end
not_found do
puts "in not found, request.fullpath #{request.fullpath}"
puts "in not found, request.request_method #{request.request_method}"
puts "in not found, request.params #{request.params}"
puts "in not found, request.class #{request.class}"
redirect '/'
end
end
AsyncQueryServer.run!
I am sure it is the upgrade to async_sinatra 1.0, because if I uncomment
#gem 'async_sinatra', '0.5.0'
it works as expected.
Interestingly, the output for the puts statements in authorized? is the same for both versions, and shows:
@auth.provided? false
undefined method `split' for nil:NilClass
@auth.provided? true
@auth.basic? true
@auth.credentials ["myusername", "mypassword"]
And here is the snippet from vb.net, based on this page, which makes the webrequest:
Private Function GetOutput(jsonDataBytes As Byte()) As String
Dim req As WebRequest
Dim res As String
' Dim cred As New Net.NetworkCredential("myusername", "mypassword")
Dim cred As New Net.NetworkCredential("myusername", "mypassword")
Dim req_str As String
req_str = _urlString & ":" & _portString & "/execfqy"
req = WebRequest.Create(req_str)
req.ContentType = "application/json"
req.Method = "POST"
req.ContentLength = jsonDataBytes.Length
req.Credentials = cred
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Try
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
res = reader.ReadToEnd()
reader.Close()
response.Close()
Catch e As WebException
Throw New NoResultsError("Request return nil results with error: " & e.Message)
res = Nothing
End Try
Return res
End Function
Any help/suggestions/redirections would be most appreciated.
TIA
Here’s how I fixed it: I abandoned the vb.net native method, and used chilkat’s http component. Works great. Here’s the code: