使用x-csrf-token身份验证连接到rest Web服务时出错



我正在groovy中写一个小脚本来做一个post-to-rest服务,我在获取令牌时成功地获得了令牌,但当将其传递给post方法时,我总是得到403错误

/*Method Get fetching token*/
def client = new RESTClient(urlWs)
client.authorization = new HTTPBasicAuthorization(user,pass)
def responseHead =  client.get(headers:["x-csrf-token": "fetch"])
def token  = responseHead?.headers['x-csrf-token']
def cookie = responseHead?.headers['set-cookie']
println "Token  -> " + token
println "Cookie -> " + responseHead?.headers['set-cookie']
/* Post Method using fetched token */
def clientPost = new RESTClient(urlWs)   
clientPost.authorization =  new HTTPBasicAuthorization(user,pass)
def responsePost =  clientPost.post(headers:["content-type":"application/json",
"cookie":cookie,
"X-CSRF-TOKEN": token ]){
json([
"DealerId": "V525",
"CustomerId": "00011"
])}

当我用邮递员或insomina测试它时,该服务运行良好,但当我尝试使用我的脚本时,却无法投递,是不是我遗漏了什么?,任何建议都将不胜感激。我使用的是groovy wslite:1.1.3-libs。

我找到了一个解决方案,我一直在使用的wslite-lib,RESTClient总是返回403 Forbiddem访问权限,即使我在get和post方法中使用相同的http实例,所以我改为Apache Httpclient组件,一切都很顺利,在groovy/grails 的代码下面

def urlWs = "http://dev.url.com/accountlookup"
def user = "user"
def pass = "pass"
/*Creates Http client instance*/
def httpclient  = HttpClients.createDefault()
def credentials =  user + ":" + pass
def encodeCred = encodeBase64String(credentials.getBytes())
def X_CSRF_TOKEN = ""
def COOKIE = ""
/*HttpGet Method for retrieving X-CSRF-Token*/
def reqGet = new HttpGet(urlWs)
reqGet.setHeader("Authorization", "Basic " + encodeCred)
reqGet.setHeader("x-csrf-token", "fetch")
println "request:------------------->"
println(reqGet.getRequestLine())
def headers = reqGet.getAllHeaders()
for (Header h : headers) {
println(h.getName() + " : " + h.getValue())
}
def getResponse = httpclient.execute(reqGet)
println "response:------------------->"
println "${getResponse.getStatusLine()}"
headers = getResponse.getAllHeaders()
for (Header h : headers) {
println(h.getName() + " : " + h.getValue())
if (h.getName() == "x-csrf-token") {
X_CSRF_TOKEN = h.getValue()
}
/*If you need get the cookie from header*/
if (h.getName() == "set-cookie") {
COOKIE = h.getValue()
}
}
println "COOKIE ---> ${COOKIE}"

/*The main POST REQUEST*/
def postRequest = new HttpPost(urlWs)
postRequest.setHeader("Authorization", "Basic ${encodeCred}")
postRequest.setHeader("Content-Type", "application/json")
postRequest.setHeader("x-csrf-token","${X_CSRF_TOKEN}")
//postRequest.setHeader("Cookie","${COOKIE}")
//postRequest.setHeader("Accept",'application/json')
def JSON_STRING = '''{"DealerId":"V525"}'''
def entity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON)
postRequest.setEntity(entity)
println "Post Execute......................................"
def postResponse = httpclient.execute(postRequest)
println "Http Post Response: " + postResponse
println "Post Response......................................"
def result = EntityUtils.toString(postResponse.getEntity())
println "Http Response: " + result
def responseCode =  postResponse.getStatusLine().getStatusCode()
println "Http Response: code " + responseCode

最新更新