Jupyter:XSRF cookie 与 POST 不匹配

Sai*_*ire 5 csrf docker jupyter jupyter-notebook

我正在尝试使用 Jupyter Rest API 使用在本地 Anaconda 上运行的 python 程序将文件传输到 docker 容器内的本地 Jupyter。

requests.get()在稍微了解如何输入令牌之后,我已经成功执行了。

现在我想执行一个requests.post()命令来传输文件。

配置:

  1. 在 Windows 的 docker 工具箱上运行的本地 docker 容器
  • docker 版本 17.04.0-ce,内部版本 4845c56
  • 张量流/张量流包括。Jupyter最新版本安装
  • jupyter_kernel_gateway==0.3.1
  1. 在 Windows 10 计算机上运行的本地 Anaconda v.4.3.14

代码:

token = token_code_provided_by_jupyter_at_startup
api_url = "http://192.168.99.100:8888/api/contents"
# getting the file's data from disk and converting into a json file
cwd = os.getcwd()
file_location = cwd+r'\Resources\Test\test_post.py'
payload = open(file_location, 'r').read()
b64payload = base64.encodestring(payload)
body = json.dumps({
            'content':b64payload,
            'name': 'test_post.py',
            'path': '/api/contents/',
            'format': 'base64',
            'type':'file'
        })
# getting the xsrf cookie
client = requests.session()
client.get('http://192.168.99.100:8888/')
csrftoken = client.cookies['_xsrf']
headers ={'Content-type': 'application/json', 'X-CSRFToken':csrftoken, 'Referer':'http://192.168.99.100:8888/api/contents', 'token':token}
response = requests.post(api_url, data=body, headers=headers, verify=True)
Run Code Online (Sandbox Code Playgroud)

返回错误

[W 12:22:36.710 NotebookApp] 403 POST /api/contents (192.168.99.1): XSRF cookie does not match POST argument
[W 12:22:36.713 NotebookApp] 403 POST /api/contents (192.168.99.1) 4.17ms referer=`http://192.168.99.100:8888/api/contents
Run Code Online (Sandbox Code Playgroud)

Xio*_*hen 6

我的解决方案受到@SaintNazaire 的启发。在我的 Chrome 浏览器中,我打开 cookie 文件夹,发现_xsrfCookies 中有重复的项目。我将它们全部删除并刷新了 Jupyter,然后一切顺利。


Sai*_*ire 0

实际上,使用 header token 进行身份验证时不需要 xsrf cookie。

headers = {'Authorization': 'token ' + token}
Run Code Online (Sandbox Code Playgroud)

参考 Jupyter Notebook 文档。

http://jupyter-notebook.readthedocs.io/en/latest/security.html