I’m facing an issue with the Spotify API in my Flutter application. Although the login appears to be successful, I receive a CANCELLED error during the redirect back to my app.
The authentication seems to work as expected in the browser, but upon redirecting, it shows an error indicating that the user has cancelled the login, even though the login was completed.
Here is the code snippet I’m using for authentication:
class AuthService {
static const clientId = '//';
static const clientSecret = '//';
static const redirectUri = 'myapp://callback';
static const String authorizationUrl = 'https://accounts.spotify.com/authorize';
static const String tokenEndPoint = 'https://accounts.spotify.com/api/token';
static const String userEndpoint = 'https://api.spotify.com/v1/me';
static Future<String?> authenticate() async {
final fullAuthUrl =
'$authorizationUrl?response_type=code&client_id=$clientId&scope=user-read-private user-read-email&redirect_uri=$redirectUri';
try {
final response = await FlutterWebAuth.authenticate(
url: fullAuthUrl, callbackUrlScheme: 'myapp');
final code = Uri.parse(response).queryParameters['code'];
if (code != null) {
return await _getToken(code);
} else {
return null;
}
} catch (e) {
if (e.toString().contains('CANCELLED')) {
print('User has canceled the authentication.');
return null;
} else {
print('An error occurred: $e');
return null;
}
}
}
static Future<String?> _getToken(String code) async {
try {
final dio = Dio();
final response = await dio.post(
tokenEndPoint,
data: {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirectUri,
},
options: Options(
headers: {
'Authorization': 'Basic ' + base64Encode(utf8.encode('$clientId:$clientSecret')),
},
),
);
if (response.statusCode == 200) {
return response.data['access_token'];
} else {
print('Token retrieval failed: ${response.statusCode}');
return null;
}
} catch (e) {
print('Error occurred while exchanging token: $e');
return null;
}
}
static Future<Map<String, dynamic>?> fetchProfile(String token) async {
///
}
After the authentication process, I would like to navigate to the main page and display user details. Can anyone help me understand why this issue is occurring?