簡體   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