通过 Ambari API 添加服务时解决 CSRF 保护错误的方法
问题描述
在使用 Ambari API 添加服务时,可能会遇到如下错误:
[root@sandbox ~]# curl -u admin:admin -i -X POST -d '{"ServiceInfo":{"service_name":"STORM"}}' http://192.168.123.129:8080/api/v1/clusters/Sandbox/services
HTTP/1.1 400 Bad Request
Set-Cookie: AMBARISESSIONID=qraouzksi4vktobhob5heqml;Path=/
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/plain
Content-Length: 107
Server: Jetty(7.6.7.v20120910)
{
"status" : 400,
"message" : "CSRF protection is turned on. X-Requested-By HTTP header is required."
}
错误提示表明 CSRF 保护已开启,需要添加 X-Requested-By HTTP 头。
解决方案
可以通过禁用 Ambari 的 CSRF 保护来解决此问题。
- 使用超级用户凭据登录 Ambari 服务器。
- 编辑配置文件:
vi /etc/ambari-server/conf/ambari.properties - 在文件底部添加以下配置:
api.csrfPrevention.enabled=false - 重启 Ambari 服务:
ambari-server restart
验证结果
再次执行 POST 命令添加服务,应能成功:
[root@sandbox ~]# curl -u admin:admin -i -X POST -d '{"ServiceInfo":{"service_name":"STORM"}}' http://192.168.123.129:8080/api/v1/clusters/Sandbox/services
HTTP/1.1 201 Created
Set-Cookie: AMBARISESSIONID=1t4c7yfbu64nw1nenrgplco7sd;Path=/
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/plain
Content-Length: 0
Server: Jetty(7.6.7.v20120910)

