我正在尝试使用需要NTLM身份验证的API。
这个curl
命令可以正常工作:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --ntlm -u user:password -d '{ "key1": "100", "key2": "1"}' http://some/api/v/12
现在我正尝试通过Go程序执行相同的操作:
package main
import (
"bytes"
"fmt"
"net/url"
"net/http"
"io/ioutil"
"log"
"github.com/Azure/go-ntlmssp"
)
func main() {
url_ := "http://some/api/v/12"
client := &http.Client{
Transport: ntlmssp.Negotiator{
RoundTripper:&http.Transport{},
},
}
data := url.Values{}
data.Set("key1", "100")
data.Set("key2", "1")
b := bytes.NewBufferString(data.Encode())
req, err := http.NewRequest("POST", url_, b)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.SetBasicAuth("user", "password")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error : %s", err)
} else {
responseData, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
responseString := string(responseData)
fmt.Println(responseString)
resp.Body.Close()
}
}
当我执行该程序时,我收到一个“无效的凭据”错误,当我在curl
命令中不包含“ --ntlm”标志时,通常会收到该错误。
您能给我一个提示,我如何用Go完成这项任务吗?
更新
从curl命令打印请求:
* About to connect() to www.xxx.xxx.com port xx (#0)
* Trying xxx.xxx.x.xxx...
* Connected to www.xxx.xxx.com (xxx.xxx.x.xx) port xx (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* Server auth using NTLM with user 'user'
> POST /some/api/v2 HTTP/1.1
> Authorization: NTLM xxxxx (44 cahracters)
> User-Agent: curl/7.29.0
> Host: www.xxx.xxx.com
> Content-Type: application/json
> Accept: application/json
> Content-Length: 0
>
< HTTP/1.1 401 Unauthorized
< Content-Type: text/html; charset=us-ascii
< Server: Microsoft-HTTPAPI/2.0
< WWW-Authenticate: NTLM xxxxx (312 characters)
< Date: Thu, xx Aug xxxx xx:xx:xx xxx
< Content-Length: 341
<
* Ignoring the response-body
* Connection
* Issue another request to this URL: 'http://some/api/v2'
* Found bundle for host www.xxx.xxx.com: 0x0000
* Re-using existing connection!
* Connected to www.xxx.xxx.com (xxx.xxx.x.xx) port xx (#0)
* Server auth using NTLM with user 'user'
> POST /api/v2 HTTP/1.1
> Authorization: NTLM xxx (176 characters)
> User-Agent: curl/7.29.0
> Host: www.xxx.xxx.com
> Content-Type: application/json
> Accept: application/json
> Content-Length: 39
>
* upload completely sent off: 39 out of 39 bytes
< HTTP/1.1 200 OK
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: application/json; charset=utf-8
< Expires: -1
< Server: Microsoft-IIS/7.5
< X-AspNet-Version: 4.0.30319
< Persistent-Auth: true
< X-Powered-By: ASP.NET
< Date: Thu, 08 Aug 2019 06:49:41 GMT
< Content-Length: 1235