Search code examples
javascriptjquerydjangoajaxoauth-2.0

Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery


I'm trying to call endpoint to generate access token using oauth in django it is working when I call the endpoint using jquery but not working when I try to call it with fetch

here is the code for fetch

fetch(`https://<domain>/o/token/`, {
            method: 'POST',
            body:{
                grant_type:'password',
                client_id: "<client-id>",
                client_secret:"<client-secret>",
                username:"<username>",
                password:"<password>"
            }
        })
        .then(res => res.json())
        .then(res => {console.log(res)});

the output is

{error: 'unsupported_grant_type'}

while when I'm calling it using jquery ajax as below its working

$.post({
            url:'https://<domain>/o/token/',
            data:{
                grant_type:'password',
                client_id: "<client-id>",
                client_secret:"<client-secret>",
                username:"<username>",
                password:"<password>"
            },
            success: function(data){
                console.log(data);
            }
        })

the output is

{access_token: '<access-token>', expires_in: 3600, token_type: 'Bearer', scope: 'read write groups', refresh_token: '<refresh-token>'}

Solution

  • I have found the fix in case someone faced the same problem

    in jquery ajax as in the following code block it converts the dictionary object to query string

    var data = "";
                for (var x in option.data) {
                    if (data != "") {
                        data += "&";
                    }
                    data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
                };
                option.data = data;
    

    and it sets the content-type header to

    'application/x-www-form-urlencoded; charset=UTF-8'
    

    so the right fetch code that will work as the jquery ajax call will be as follow

    fetch(`https://<domain>/o/token/`, {
                method: 'POST',
                headers: {
                    "Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body:'grant_type=password&client_id=<client-id>&client_secret=<client-secret>&username=<username>&password=<password>'
            })
            .then(res => res.json())
            .then(res => {console.log(res)});