Search code examples
httprustreqwest

Rust: Reqwest Post Request Failing - States Grant_Type Not Supplied in Body (MIME is application/x-www-form-urlencoded)


I am having an issue passing data to Reqwest. I am using serde_urlencoded to create a string for a POST request. I receive the error below. I have confirmed that the data I use for request is correct with curl. It leads me to believe my body or headers are incorrect.

May someone please help me understand what is going wrong here with the request?

Error: {\"error\":\"unsupported_grant_type\",\"error_description\":\"grant_type parameter is missing\"}

Vec<u8> body and HeaderMap == Hashmap<String, Vec<String>>

    // application/x-www-form-urlencoded Mime type body
    let body = serde_urlencoded::to_string([
        ("grant_type", "authorization_code"),
        ("code", "authcode"),
        ("redirect_uri", "redirect.com"),
        ("code_verifier", "workingVerifier" ),
        ("client_id", "SomeID"),
        ("client_secret", "SomeSecret"),
    ])?;

    let body = serde_json::to_vec(&body)?;

 let mut headers: HeaderMap = HeaderMap::new();
    headers.insert(
        "Authorization".to_string(),
        vec![format!("Basic {}", generate_auth_string(conf).await?)],
    );
    headers.insert(
        "Content-Type".to_string(),
        vec!["application/x-www-form-urlencoded".to_string()],
    );

Reqwest

 let response = reqwest::Client::new()
            .request(method, &req.url)
            .headers(headers)
            .body(body)
            .send()
            .await

Solution

  • Per @kmdreko I needed to change my body to not use serde_json.

    let body = body.as_bytes().to_vec();