Laravel API cURL请求Python

我遵循了这个Laravel令牌API教程: http://rjv.im/post/95988160186/api-token-authentication-with-laravel-and-sentry-part 。 我写了以下cURL请求与我的API通信:</ p>

  curl -H“X-Auth-Token:tokenhere”http:// localhost:8000 / account 
</ code> </ pre>

请求正常工作,并准确返回预期数据。 当我将其翻译为Python时,我收到 urllib2.HTTPError:HTTP错误401:未授权</ code> </ p>

  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
</ code> </ pre>

如果我使用基本身份验证而不是X-Auth-Token传递用户凭据,请求将按预期工作:</ p>

   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()
</ code> </ pre>

非常感谢任何帮助。 </ p>
</ div>

展开原文

原文

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.

dtrj74376
dtrj74376 最后,大多数auth-token机制都有TTL/expiration/etc.curl命令在Python脚本失败后是否正常工作,或者它是否只是在过去工作?
5 年多之前 回复
dongtie0929
dongtie0929 其次,为了调试这个,你需要先看一下你发送的不同内容。您能让服务器记录完整的请求,以便比较它们吗?或者在Wireshark中查看它们?或者只是运行类似nc-kl8000而不是你的服务器,并在你的curl命令和Python程序试图与之交谈时观察它打印出来的内容?
5 年多之前 回复
duan198811
duan198811 首先,您如何解析服务器端的X-Auth-Token标头?因为通常情况下,标题是在冒号之后用空格发送的-这就是curl将如何发送所有其余标题,以及urllib2将如何发送所有标题,包括您添加的标题。如果您的服务器实际上期望'X-Auth-Token:tokenhere'并拒绝'X-Auth-Token:tokenhere',那么您需要在服务器端修复该错误。
5 年多之前 回复

1个回答



教程中遗漏了一些内容。 在令牌表中有一列:</ p>

$ table-&gt; string('client'); </ code> </ p>

您发送请求的客户端非常重要。 我正在使用 https://github.com/hisorange/browser-detect 来检测来自哪个客户端 我收到了请求。</ p>

但是现在我将尝试查看用户代理。 在我的laravel代码中,我只记录了每个请求以查看以下代码发生的情况:</ p>

  Route :: filter('auth.token',function($ route,$ request)  )
{
....

Log :: info($ request);

....
}
</ code> </ pre>

现在,让我们看看:</ p>

当我从命令行使用curl时:</ p>

  curl -u user@example.com:password-  X GET http:// localhost:8000 / account 
</ code> </ pre>

我的用户代理是</ p>

  User-Agent:  curl / 7.32.0 
</ code> </ pre>

我使用上面的代码从python发送了相同的代码,用户代理是:</ p>

  User-Agent:Python-urllib / 2.7 
</ code> </ pre>

啊!一定是它。你必须使用Basic Auth至少验证一次用户,它会给出 您是一个令牌,该令牌仅对该客户有效。在第一部分 http://rjv.im/post/78940780589/api-token-authentication-with-laravel-and-sentry-par 教程中没有这样的条件。 在评论中,我收到的人发布了一个关于如何支持多个客户端的查询,所以这个例子是为了解决这个问题。</ p>

除此之外,我可以建议这个库: https://github.com/chrisbjr/api-guard 它支持速率限制,易于与Sentry集成。 这与我的教程有点不同。 使用我的解决方案,您可以使用Basic Auth或Token命中任何端点。 使用上面的库,只允许令牌,因此有专门的路由来生成令牌。 让我知道它是怎么回事。</ p>
</ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问