groovy - 在请求标头中传递 JWT 在 groovy 脚本中不起作用
问题描述
我正在尝试通过 groovy 脚本从 CMDB(BMC 中庭)访问 CI 数据,它分两步进行。
首先发送 POST 请求登录 api 并获取授权令牌。
其次是在后续的 api 调用中使用这个令牌。
我已经在邮递员中测试了这两个 API,它们工作正常。
获取令牌的部分在 groovy 脚本中运行良好,但使用此令牌获取 CI 数据的部分返回错误 json:
"JsonResponse is[{"messageType":"ERROR","messageText":"控制记录中必须提供用户名","messageAppendedText":null,"messageNumber":149}]"
这是有趣的部分,我回到邮递员并在授权标头中放置了一个新生成的令牌,它给了我与上面提到的相同的错误 json。当我在授权标头中附加带有令牌值的“AR-JWT”时 - 它工作正常!
我尝试在标头中传递不同的值,例如 - AuthenticationInfoValue.authentication = username 、 Authorization-Type 、用户名和密码等,但似乎没有任何效果。
我已经检查了 BMC 官方网站的文档,但据此我做的一切都是正确的。如果有人能指出我做错了什么,那真的很有帮助。
这是 groovy 脚本
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')
//post call to get the token
def token
def httpRequester = new
groovyx.net.http.HTTPBuilder("http://<localhost>:<port>/api/jwt/login");
httpRequester.request(groovyx.net.http.Method.POST) { req ->
requestContentType = groovyx.net.http.ContentType.URLENC
body = [username:'user', password:'pass']
response.success = { resp , reader ->
println "response success"
httpResponse = resp
println "httpResponse : "+httpResponse
token = reader.getText()
println "token : "+token
}
response.failure = { resp , reader ->
println "response failure"
httpResponse = resp
println "httpResponse : "+httpResponse
token = reader.getText()
println "token : "+token
}
}
//Get call to fetch the CI Data
httpRequester = new groovyx.net.http.HTTPBuilder("http://<localhost>:<port>/api/arsys/v1/entry/AST:ComputerSystem")
def finalToken = "AR-JWT" + " " + token ;
httpRequester.request(groovyx.net.http.Method.GET) { req ->
println "Inside request"
def headerMap = ['Content-Type': 'application/x-www-form-urlencoded' ,
'Authorization': finalToken]
httpRequester.setHeaders(headerMap)
println "headers : "+httpRequester.getHeaders()
requestContentType = groovyx.net.http.ContentType.URLENC
response.success = { resp, json ->
println "response success"
httpResponse = resp
jsonResponse = json
}
response.failure = { resp, json ->
println "response failure"
httpResponse = resp
jsonResponse = json
}
}
jsonResponse = new groovy.json.JsonBuilder(jsonResponse);
println "JsonResponse is" +jsonResponse.toString();
解决方案
经过大量调试后,我发现了这个问题,事实证明这很愚蠢。
在 GET API 调用中必须设置如下标头。
headers.'Content-Type'='application/x-www-form-urlencoded'
headers.'Authorization'=finalToken
并注释掉或删除以下行。
//def headerMap = ['Content-Type': 'application/x-www-form-urlencoded' , 'Authorization': finalToken]
//httpRequester.setHeaders(headerMap)
推荐阅读
- excel - 如何在 C 列中放置一个数字 X(如果单元格为空),其中 X 等于 B 列中的同一行减去 1?
- arrays - 动态添加输入元素以形成反应
- javascript - 获取错误 DOMException:运行扩展程序以将文本从 PDF 复制到剪贴板时,文档未聚焦
- c++ - 关于真正使用抽象类的问题
- c# - 如何根据 C# 中的模型数量动态构造 JSON 键名?
- swift - 为什么 Swift 会在 stringFromData 的开头意外插入“Optional”?
- c# - 如何在 Azure Function 中禁用强制 https 重定向?
- reactjs - React MobX - 装饰器 + useObserver 不会重新渲染
- amazon-web-services - AWS 网络负载均衡器和使用 AWS Fargate 的 TCP 流量
- ios - 这些结构标识符之间有什么不同