drutjkpsr67393592 2018-11-07 10:56
浏览 52

从OAuth请求客户端获取令牌

I’ve the following code which I want to get the token from the request , I pass the API/ClientSecret/ClientID

r := fmt.Sprintf("https://tenenat.host.com/oauth/token?grant_type=client_credentials&response_type=token&client_id=%s&client_secret=%s", CI, CS)
req, err := http.NewRequest(http.MethodPost, r, nil)
req.Header.Set("accept", "application/json")
res, err := httpClient.Do(req)
if err != nil {
    fmt.Println(os.Stdout)
    var t OAuthAccessResponse
    if err := json.NewDecoder(res.Body).Decode(&t); err != nil {
        fmt.Println(os.Stdout, "could not parse JSON response: %v", err)
    }
    defer res.Body.Close()
}

When running it I got error :

http 400 bad request .

Any idea if I miss something in the request ?

Im not able to format the code right :)

  • 写回答

1条回答 默认 最新

  • duanpei4455 2018-11-07 12:15
    关注

    If avoidable, you should not be placing sensitive data, such as client secret, in the URL string. It is less secure than using the message body: for example it may be captured in logs and site traffic analytics that end up being shared with third parties.

    Instead, do a POST with a JSON body:

    type TokenRequest struct {
        GrantType    string `json:"grant_type"`
        ResponseType string `json:"response_type"`
        ClientID     string `json:"client_id"`
        ClientSecret string `json:"client_secret"`
    }
    tokenReq := &TokenRequest{
        GrantType:    grantType,
        ResponseType: responseType,
        ClientID:     clientID,
        ClientSecret: clientSecret,
    }
    body, err := json.Marshal(tokenReq)
    if err != nil {
        log.Errorf("Failed to marshal request body: %s", err)
    }
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
    if err != nil {
        log.Errorf("Failed to create request: %s", err)
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Accept", "application/json")
    res, err := httpClient.Do(req)
    

    Update

    OP is now getting a statuscode 401 response. 401 is unauthorized. You probably need to authenticate to the API. For example, if you have a bearer token, add a header for it prior to making your request:

    req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearer))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!