I’m working with Twitch authentication and running into a strange issue with the callback URL format. When I redirect users to authorize my application, the response comes back with a hash (#) character instead of the expected question mark (?) for URL parameters.
if (isset($_POST['token'])) {
$_SESSION['auth_token'] = $_POST['token'];
$userInfo = file_get_contents("https://api.twitch.tv/kraken?oauth_token=" . $_SESSION['auth_token']);
$decodedUserInfo = json_decode($userInfo, true);
echo $_SESSION['user'] = $decodedUserInfo['token']['user_name'];
} else {
header('Location: https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id={myClientID}&redirect_uri=http://localhost/myapp/callback');
}
The callback URL I receive looks like http://localhost/myapp/callback#token={MyToken}&scope= but I expected it to be http://localhost/myapp/callback?token={MyToken}&scope=. The hash symbol makes it impossible to access the token via $_GET. Has anyone encountered this before or knows how to handle this properly?
The presence of the hash symbol indicates that you are using the implicit grant flow, which is designed for client-side applications. I faced this issue as well when working with Twitch OAuth. Tokens are returned in the URL fragment for security reasons, preventing them from being sent to your server. You have two possible solutions: use JavaScript to extract the token from window.location.hash and send it to your PHP script, or switch to the authorization code flow. I recommend the second approach, as it is more secure for server-side PHP and eliminates the complications associated with fragments.
You’re seeing the hash symbol because response_type=token triggers the implicit grant flow. This flow returns tokens in the URL fragment (after #) instead of query parameters. Since fragments don’t get sent to the server, PHP’s $_GET can’t capture them. Switch to response_type=code instead. This gives you an authorization code as a query parameter that you can exchange for an access token with a server-to-server request. The implicit flow you’re using now is meant for JavaScript apps that read fragments client-side. This change should fix your issue and let you handle tokens properly in PHP.
i ran into that too! the hash is there cuz of the implicit flow, which puts the token in the url fragment. your server can’t access it like that. u gotta use js to get it first or just go for the authorization code flow instead. it’s simpler for backend stuff, trust me!