0

I'm trying to use the fetch API in vanilla JavaScript to generate a token provided by Django OAuth Toolkit. The application I've created in DOT uses the "Resource owner password-based" authorization grant type. My code looks like this (grant_type, username and password are provided through request.formData()):

const data = await request.formData();
const oauth = await fetch(`${API_ROOT}/o/token`, {
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Basic ${Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')}`
    },
    body: data
});

This request imitates a successful GET request I've created using Insomnia (with Multipart Form data for grant_type, username and password + CLIENT_ID and CLIENT_SECRET as the username and password in Basic Auth). In other words, I don't understand why the JavaScript fetch request does not work even though it is supposed to be identical to the Insomnia request. The JavaScript fetch request returns a 400 error. When I remove the Content-Type header, I get a 500 error. What am I doing wrong?

EDIT: It may be worth noting that I am making this fetch call within a SvelteKit application.

lapmir
  • 1
  • 1
  • you should not set `Content-Type` header. can you check in the backend side why 500 error is happening? You can refer [this](https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api/46640744#46640744) for why `Content-Type` is not to be set – Kaneki21 Oct 15 '22 at 06:43
  • Thanks for this, I still haven't identified the issue but I will stop attempting to set Content-Type. – lapmir Oct 16 '22 at 01:19

1 Answers1

0

As it turns out, in this particular case I DID need to set Content-Type. I found this answer: Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery

My code works as follows:

const data = await request.formData();
const oauth = await fetch(`${API_ROOT}/oauth/token/`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
        Authorization: `Basic ${Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')}`,
    },
    body: formDataToUrlEncoded(data)
});

The formDataToUrlEncoded function roughly ressembles the one posted in the above post:

export function formDataToUrlEncoded(formData) {
    var url_encoded = '';
    for (var pair of formData) {
        if (url_encoded != '') {
            url_encoded += '&';
        }
        url_encoded += encodeURIComponent(pair[0]) + '=' + encodeURIComponent(pair[1]);
    }
    return url_encoded;
}
lapmir
  • 1
  • 1