0

I am trying to set up authentication with Auth0 in a Flutter application and I can't get Auth0 to redirect me to my dashboard after authenticating. It returns me to the login page, which makes no sense to me since it's not the default route and isn't specified in the callback URL. I am using GoRouter and flutter_appauth. I tried to attach anything useful. Can anyone tell me what I'm missing?

This is my login function:

import 'package:flutter/foundation.dart';
import 'package:flutter_appauth/flutter_appauth.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

const appAuth = FlutterAppAuth();

login() {
  final authorizationTokenRequest = AuthorizationTokenRequest(
    dotenv.env['AUTH0_CLIENT_ID']!,
    dotenv.env['AUTH0_REDIRECT_URI']!,
    scopes: ['openid', 'profile', 'email', 'offline_access'],
    issuer: dotenv.env['AUTH0_ISSUER']!,
  );
  final result = appAuth.authorizeAndExchangeCode(authorizationTokenRequest);
  if (kDebugMode) {
    print(result);
  }
  return result;
}

This is where I call login():

import 'package:flutter/material.dart';
import 'package:counter42/services/auth_service.dart';

class Welcome extends StatefulWidget {
  const Welcome({super.key});

  @override
  State<Welcome> createState() => _WelcomeState();
}

class _WelcomeState extends State<Welcome> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Welcome to Counter42'),
      ),
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  login();
                },
                child: const Text('Login'),
              ),
              const Text('Please login to continue'),
            ],
          ),
        ),
      ),
    );
  }
}

This is my (sanitized) .env setup:

BUNDLE_IDENTIFIER=com.xxxxxxxx.counter42

AUTH0_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AUTH0_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AUTH0_DOMAIN=dev-xxxxxxxx.us.auth0.com
AUTH0_ISSUER=https://dev-xxxxxxxx.us.auth0.com
AUTH0_REDIRECT_URI=com.xxxxxxxx.counter42://dashboard

This is the callback URL in my Auth0 dashboard: com.xxxxxxxx.counter42://dashboard

This is my main.dart with the routing:

import 'package:counter42/screens/dashboard.dart';
import 'package:counter42/screens/player_counter.dart';
import 'package:counter42/screens/preferences.dart';
import 'package:counter42/screens/welcome.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

Future main() async => {await dotenv.load(fileName: '.env'), runApp(App())};

class App extends StatelessWidget {
  App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
      title: 'Counter42 Router',
    );
  }

  final GoRouter _router = GoRouter(
    routes: <GoRoute>[
      GoRoute(
        path: '/',
        builder: (context, state) => const Welcome(),
      ),
      GoRoute(
        path: '/dashboard',
        builder: (context, state) => const Dashboard(),
      ),
      GoRoute(
        path: '/preferences',
        builder: (context, state) => const Preferences(),
      ),
      GoRoute(
        path: '/player_counter',
        builder: (context, state) => const PlayerCounter(),
      )
    ],
  );
}

And this is my build.gradle:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 33
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.xxxxxxxx.counter42"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion 21
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
        manifestPlaceholders += [
            'appAuthRedirectScheme': 'com.xxxxxxxx.counter42'
        ]
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
Bus42
  • 130
  • 6
  • Your redirect _url_ isn't a valid URL. – Phil Oct 07 '22 at 01:34
  • The example from Auth0 is `com.auth0.flutterdemo://login-callback` the only difference is my package name and endpoint. ie: `://`. If the URL were not valid it would have thrown an error rather than redirected to my application. Do you have any suggestions? – Bus42 Oct 07 '22 at 15:54

0 Answers0