Search code examples
flutteroauthoauth-2.0spotify

Flutter: Oauth2 - Problems with redirect uri


I want to set up the oAuth authentication of the Spotify API in my Flutter app. I chose the flutter_web_auth 0.1.1 package. So far, I have managed that the user can log in to Spotify. After logging in, the user should be redirected back to my app. That does not work. Spotify always redirects the user to another website and not back to the app. How do I close the WebView after the user logging in and redirect the user to my app?

import 'package:flutter/material.dart';
import 'package:flutter_web_auth/flutter_web_auth.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    authenticate();
  }

  void authenticate() async {
    // Present the dialog to the user
    final result = await FlutterWebAuth.authenticate(
      url:
          "https://accounts.spotify.com/de/authorize?client_id=78ca499b2577406ba7c364d1682b4a6c&response_type=code&redirect_uri=https://partyai/callback&scope=user-read-private%20user-read-email&state=34fFs29kd09",
      callbackUrlScheme: "https://partyai/callback",
    );

// Extract token from resulting url
    final token = Uri.parse(result).queryParameters['token'];
    print('token');
    print(token);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Web Auth example'),
        ),
        body: Center(
          child: Text(
            'test',
          ),
        ),
      ),
    );
  }
}

android/app/src/main/AndroidManifest.xml

<activity android:name="com.linusu.flutter_web_auth.CallbackActivity" >
            <intent-filter android:label="flutter_web_auth">
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="https://partyai/callback" />
            </intent-filter>
        </activity>

enter image description here


Solution

  • The callbackUrlScheme should be partyai, the redirect_uri should be partyai:/ and the AndroidManifest.xml android:scheme value should be partyai.