Search code examples
sonos

ERR_ABORTED 403 (Forbidden)


I'm trying to build a program which can control my Sonos Speaker. I'm following the instructions over at https://developer.sonos.com/build/direct-control/authorize/.

The first step - getting the authorization code - is working as intended but the problem I'm facing arises when I try to send the authorization code per POST request with the following code:

const redirect_uri = "https%3A%2F%2Fsonoscontrol-c4af4.web.app%2F";
const redirect_url = "https://sonoscontrol-c4af4.web.app/";
const client_id =  // API Key (deleted value for safety)
const secret =     // Secret (deleted value for safety)
const auth_url = `https://api.sonos.com/login/v3/oauth?client_id=${client_id}&response_type=code&state=testState&scope=playback-control-all&redirect_uri=${redirect_uri}`;

function GetAccessToken() {
    var target_url = "https://api.sonos.com/login/v3/oauth/access/";
    var authCode = GetAuthCode();
    var encoded_msg = btoa(client_id + ":" + secret); // base64-encodes client_id and secret using semicolon as delimiter
    
    var params = "grant_type=authorization_code" + `&code=${authCode}` + `&redirect_uri=${redirect_uri}` + `&client_id=${client_id}`;

    var myHeaders = new Headers({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST',
        'Authentication': `Basic {${encoded_msg}}`,
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    });
    
    fetch(target_url, {
        method: "POST",
        mode: "no-cors",
        credentials: "include",
        redirect: "follow",
        headers: myHeaders,
        body: params
    }).then((res) => {
        console.log(res.responseText);
    }).catch(function(error) {
        console.log(error);
    });
}
function GetAuthCode() {
    return (new URLSearchParams(location.search)).get('code');  // returns authorization code from URL
}

Now I get the following error when trying to send the POST request: POST https://api.sonos.com/login/v3/oauth/access/ net::ERR_ABORTED 403 (Forbidden)

I am using a Cloud Firebase app as webserver and added the correct redirect URL in the credentials.

What could be the problem for this error message?


Solution

  • I noticed a couple of things in your code that may be causing your 403 Forbidden issue.

    1. Your "Authentication" header should be "Authorization", eg: "Authorization: Basic {YourBase64EncodedClientId:SecretGoesHere}"
    2. Your "target_url" has a trailing slash, it should be "https://api.sonos.com/login/v3/oauth/access"
    3. Your query parameters "params" are including the client_id on the token request, which isn't necessary, though I don't believe it will cause an error.

    Addressing the above should hopefully resolve your issue!

    Thanks,

    -Mark