Asana returning 400 error for go cde but works fine on Nodejs

21 Views Asked by At

I have this nodeJS code which works fine


export const createAsanaAuthUrl = () => {
  // Store this in DB
  const codeChallenge = crypto
    .createHash('sha256')
    .update(CODE_VERIFIER)
    .digest('base64')
    .replace(/=/g, '')
    .replace(/\+/g, '-')
    .replace(/\//g, '_');
  const udid = uuidv4();
  const url = `${ASANA_AUTH_BASE}/oauth_authorize?client_id=${ASANA_CLIENT_ID}&redirect_uri=${ASANA_REDIRECT_URL}&response_type=code&state=${udid}&code_challenge_method=S256&code_challenge=${codeChallenge}`;
  return url;
};


export const getAsanToken = async (code: string) => {
  const params = {
    grant_type: 'authorization_code',
    client_id: ASANA_CLIENT_ID,
    client_secret: ASANA_CLIENT_SECRET,
    redirect_uri: ASANA_REDIRECT_URL,
    code,
    code_verifier: CODE_VERIFIER,
  };
  const { refresh_token, access_token } = (
    await axios.post(`${ASANA_AUTH_BASE}/oauth_token`, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })
  ).data;

but the equivalent go code is throwing 400 error


func CreateAsanaAuthUrl(env *config.Env) string {
    hash := sha256.Sum256([]byte(constants.AsanaCodeVerifier))
    codeChallenge := base64.URLEncoding.EncodeToString(hash[:])
    codeChallenge = strings.TrimRight(codeChallenge, "=")
    udid := uuid.New().String()
    url := fmt.Sprintf("%s/oauth_authorize?client_id=%s&redirect_uri=%s&response_type=code&state=%s&code_challenge_method=S256&code_challenge=%s", constants.AsanaAuthBase, env.AsanaClientId, env.AsanaRedirectUrl, udid, codeChallenge)
    return url
}

func GetAsanaToken (args domain.GetTokenArgs)  (*domain.ServiceAuthReturn, error) {
    env := args.Env
    params := TokenAsanaRequest{
    GrantType:    "authorization_code",
    ClientID:     env.AsanaClientId,
    ClientSecret: env.AsanaClientSecret,
    RedirectURI:  env.AsanaRedirectUrl,
    Code:         args.Code,
    CodeVerifier: constants.AsanaCodeVerifier,
    }
    fmt.Printf("p: %+v\n", params)
    url := constants.AsanaAuthBase + "/oauth_token"
    reqBody, err := json.Marshal(params)
    fmt.Printf("Url: %v", url)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Println("Error", err) // log
        return nil, fmt.Errorf("error sending Asana auth request: %s", err.Error())
    }
    defer resp.Body.Close()
    if resp.StatusCode >= 400 {
    // server returned an error
        errorBody, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Println("Error:", err) // log
            return nil, fmt.Errorf("error reading error response body: %s", err.Error())
        }
        log.Printf("Error response body: %s", string(errorBody)) // log error response body
        return nil, fmt.Errorf("error getting asana auth token %d", resp.StatusCode)
    }

    var result struct {
        AccessToken string `json:"access_token"`
        RefreshToken string `json:"refresh_token"`
    }

It is throwing error here

        log.Printf("Error response body: %s", string(errorBody)) // log error response body

With status code being 400

Any idea what I could be doing wrong?

0

There are 0 best solutions below