0

我正在尝试通过 API 仅通过终端登录我的 DKAN 实例,但我不断收到CSRF validation failed错误消息。这就是我正在做的事情。

首先我登录一个收集 CSRF 令牌:

curl -X POST -i -H "Content-type: application/json" -H "Accept: application/json" -c cookies.txt -X POST http://192.168.33.10/?q=api/dataset/user/login -d '{
    "username":"admin",
    "password":"mypassword"
}'

这将输出以下内容:

HTTP/1.1 200 OK
Date: Mon, 24 Apr 2017 15:34:45 GMT
Server: Apache/2.4.18 (Ubuntu)
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control: no-cache, must-revalidate
X-Content-Type-Options: nosniff
Vary: Accept
Set-Cookie: SESS37d01773a34cec5fc5828d6b58243814=ybUPfN7scbsTJnJQNf_yWkaqIBQlDJOBLYXDj8bdpO4; expires=Wed, 17-May-2017 19:08:05 GMT; Max-Age=2000000; path=/; HttpOnly
Content-Length: 807
Content-Type: application/json

{"sessid":"ybUPfN7scbsTJnJQNf_yWkaqIBQlDJOBLYXDj8bdpO4","session_name":"SESS37d01773a34cec5fc5828d6b58243814","token":"Of5m-_2V9vwLYmI49aArgd6K9HSqVJwpQwSfQH1jlBU","user":{"uid":"1","name":"admin","mail":"emailaddressremoved@mailservice.com","theme":"","signature":"","signature_format":null,"created":"1493037751","access":"1493047878","login":1493048085,"status":"1","timezone":"Europe/London","language":"","picture":null,"init":"emailaddressremoved@mailservice.com","data":false,"uuid":"21e95002-1c5a-4b1d-a515-8c8a245025c5","roles":{"2":"authenticated user"},"field_about":[],"og_user_node":{"und":[{"target_id":"1"},{"target_id":"2"},{"target_id":"3"}]},"rdf_mapping":{"rdftype":["sioc:UserAccount"],"name":{"predicates":["foaf:name"]},"homepage":{"predicates":["foaf:page"],"type":"rel"}}}}

接下来,我token从上面的输出中获取并将其放入以下命令以登录 DKAN 并创建一个新数据集:

curl -X POST -i -H "Content-type: application/json" -H "X-CSRF-Token:Of5m-_2V9vwLYmI49aArgd6K9HSqVJwpQwSfQH1jlBU" -b cookies.txt -X POST http://192.168.33.10/?=api/dataset/node -d '{
    "title":"A node created via DKAN REST API",
    "type":"dataset",
    "body": {
        "und": [{"value": "This should be the description"}]
    }
}'

此命令的输出是:

HTTP/1.1 403 Forbidden
Date: Mon, 24 Apr 2017 15:35:03 GMT
Server: Apache/2.4.18 (Ubuntu)
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control: no-cache, must-revalidate
X-Content-Type-Options: nosniff
Content-Length: 41
Content-Type: text/html; charset=UTF-8

403 Access Denied: CSRF validation failed

我一直在关注文档中的 API 教程。我错过了什么吗?

4

1 回答 1

0

我解决了我自己的问题。除了第二个命令的X-CSRF-TOKEN标题后缺少空格外,一切都是正确的。curl

该命令应该是:

curl --request POST --include --header "Content-type: application/json" --header "X-CSRF-Token: Of5m-_2V9vwLYmI49aArgd6K9HSqVJwpQwSfQH1jlBU" --cookie cookies.txt --request POST http://192.168.33.10/?=api/dataset/node -data '{
    "title":"A node created via DKAN REST API",
    "type":"dataset",
    "body": {
        "und": [{"value": "This should be the description"}]
    }
}'

注意 和 之间的"X-CSRF-Token:空格Of5m-_2V9vwLYmI49aArgd6K9HSqVJwpQwSfQH1jlBU"。显然这是非常重要的。我还将标签更改为更易读的形式,以帮助我了解发生了什么。

于 2017-04-25T13:05:15.400 回答