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 :)
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)
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))