繁体   English   中英

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

[英]Error connecting to rest webservice with x-csrf-token authentication

我正在 groovy 中编写一个小脚本来发布到 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"
                            ])}

当我使用 postman 或 insomina 对其进行测试时,该服务工作正常,但是当我尝试使用我的脚本无法发布帖子时,是否有我遗漏的东西?任何建议将不胜感激。 我正在使用 groovy-wslite:1.1.3 库。

我找到了一个解决方案,我一直在使用的 wslite lib,即使我在 get 和 post 方法中使用相同的 http 实例,RESTClient 总是返回 403 Forbiddem 访问,所以我更改为 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM