Using fetch to get access token from Django OAuth Toolkit

550 views Asked by At

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.

1

There are 1 answers

0
lapmir On

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;
}