drodsh7940 2017-01-09 05:25
浏览 352
已采纳

Golang HTTP基本认证

I am new in golang.

I am trying to call JIRA rest api with basic auth, but getting following error

&{401 Unauthorized 401 HTTP/2.0 2 0
map[X-Content-Type-Options:[nosniff]
Set-Cookie:[JSESSIONID=E08620; Path=/;
Secure; HttpOnly studio.crowd.tokenkey="";
Domain=.test.atlassian.net; Expires=Thu, 01-Jan-1970 00:00:10
GMT; Path=/; Secure; HttpOnly studio.crowd.tokenkey="";
Domain=.test.atlassian.net; Expires=Thu, 01-Jan-1970 00:00:10
GMT; Path=/; Secure; HttpOnly] Server:[nginx] Date:[Mon, 09 Jan 2017
05:18:29 GMT] Content-Type:[text/html;charset=UTF-8]
X-Arequestid:[648x20759x1] X-Seraph-Loginreason:[AUTHENTICATED_FAILED]
Www-Authenticate:[OAuth
realm="https%3A%2F%2Ftest.atlassian.net"]] {0xc42039b900} -1 []
false false map[] 0xc4200ce0f0 0xc4202b0420}

My code is

package main

import (
    "fmt"
    "log"
    "net/http"
)

const (
    USERNAME = ""
    PASSWORD = ""
    URL      = "https://test.atlassian.net/rest/api/2/issue/SLUB-7194"
)

func main() {
    req, err := http.NewRequest("GET", URL, nil)
    req.SetBasicAuth(USERNAME, PASSWORD)

    req.Header.Set("Accept", "application/json")
    req.Header.Set("Content-Type", "application/json")

    cli := &http.Client{}
    resp, err := cli.Do(req)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp);
}

Am I doing something wrong?

Thanks in advance

  • 写回答

1条回答 默认 最新

  • douyou2368 2017-01-09 05:37
    关注

    As seen in Netflix-Skunkworks/go-jira/cli.go, you might need to login first, then request your jira ticket.

    func (c *Cli) makeRequest(req *http.Request) (resp *http.Response, err error) {
        req.Header.Set("Accept", "application/json")
        req.Header.Set("Content-Type", "application/json")
    
        if source, ok := c.opts["password-source"]; ok && !strings.HasSuffix(req.URL.Path, "/rest/auth/1/session") {
            user, _ := c.opts["user"].(string)
            password := c.GetPass(user)
            if password == "" {
                log.Warning("No password for user %s in %s, please run the 'login' command first", user, source)
            } else {
                req.SetBasicAuth(user, password)
            }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多