
I'm having a similar issue when trying to redirect to the Spotify authorization page. I am using Axios to send the requests.
Clicking the link in the first error of the console sends me to the authorization page, so I know the URL parameters are correct. However when I click the "authorize Spotify" button on my app, I am not redirected.
here is my authorization link:
https://accounts.spotify.com/en/authorize?client_id=760d4229d20a41eebca3be251aa015f9&response_type=c...
here is my source code:
import logo from "./assets/images/SpotifyLogo.png";
import React from "react";
import axios from "axios";
const clientId = "760d4229d20a41eebca3be251aa015f9";
const redirectUri = "http://localhost:8080";
const scope = "user-read-private user-read-email";
const authUrl = "https://accounts.spotify.com/authorize";
const tokenUrl = "http://accounts.spotify.com/api/token/";
var authCode;
export default function SpotifyAuthorizer() {
return (
<div className="card">
<img
src={logo}
alt="Spotify Logo"
width="350px"
/>
<p className="text"> Spotify Access Required!</p>
<button
className="btn"
onClick={AuthorizeSpotify}>
Authorize Spotify
</button>
</div>
);
}
async function AuthorizeSpotify() {
const generateRandomString = (length) => {
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const values = crypto.getRandomValues(new Uint8Array(length));
return values.reduce((acc, x) => acc + possible[x % possible.length], "");
};
const codeVerifier = generateRandomString(64);
const sha256 = async (plain) => {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
return window.crypto.subtle.digest("SHA-256", data);
};
const base64encode = (input) => {
return btoa(String.fromCharCode(...new Uint8Array(input)))
.replace(/=/g, "")
.replace(/\+/g, "-")
.replace(/\//g, "_");
};
const hashed = await sha256(codeVerifier);
const codeChallenge = base64encode(hashed);
RequestUserAuthorization(codeChallenge);
}
async function RequestUserAuthorization(codeChallenge) {
const params = {
client_id: clientId,
response_type: "code",
redirect_uri: redirectUri,
scope: scope,
code_challenge_method: "S256",
code_challenge: codeChallenge,
}
axios
.get(authUrl, {
params: params,
}).then(function(response) {
console.log(response.data);
authUrl.search = new URLSearchParams(params).toString();
window.location.href = authUrl;
})
.catch(function(error) {
console.log(error.stack);
});
const urlParams = new URLSearchParams(window.location.search);
authCode = urlParams.get('code');
}
async function RequestAccessToken(codeVerifier) {
axios
.post(tokenUrl, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
params: {
grant_type: "authorization_code",
redirect_uri: redirectUri,
client_id: clientId,
code_verifier: codeVerifier,
},
})
.catch(function (error) {
console.log(error.stack);
});
}