auth0 / auth0-flutter

Auth0 SDK for Flutter
https://pub.dev/documentation/auth0_flutter/latest/
Apache License 2.0
61 stars 41 forks source link

Flutter web not returning any credential after completion of login with audience. #298

Closed ranjitIN closed 1 year ago

ranjitIN commented 1 year ago

Checklist

Description

i am trying to perform login in flutter web by passing audience but the onload function does not return any credentials after completion of login with auth0. if i try to login with out passing audience it working fine. i also try this sample app i am facing the same issue.

on load function

@override
  void initState() {
    super.initState();
    auth0 = Auth0(domain,clinetId);
    auth0Web = Auth0Web(domain,clinetId);
    // webAuth =
    //     auth0!.webAuthentication(scheme: dotenv.env['AUTH0_CUSTOM_SCHEME']);

    if (kIsWeb) {
      auth0Web!.onLoad().then((final credentials) => setState(() {
            _output = credentials?.idToken ?? '';
            _isLoggedIn = credentials != null;
          }));
    }
  }

login function

Future<void> webAuthLogin() async {
    String output = '';

    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      if (kIsWeb) {
        return auth0Web.loginWithRedirect(redirectUrl: 'http://localhost:3000',audience: audience);
      }

      final result = await webAuth.login();

      output = result.idToken;
    } catch (e) {
      output = e.toString();
    }

    setState(() {
      _isLoggedIn = true;
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _output = output;
    });
  }

Reproduction

  1. just pass audience on web login

Additional context

No response

auth0_flutter version

1.2.1

Flutter version

3.10.2

Platform

Web

Platform version(s)

No response

Widcket commented 1 year ago

Hi @ranjitIN, thanks for raising this.

I can only reproduce this when I don't configure the Allowed Web Origins URL:

Screenshot 2023-08-02 at 11 43 37 PM

Have you configured this value in your Auth0 app's settings, as explained here?

ranjitIN commented 1 year ago

All these things are configured and it's working fine if I am not passing the audience . When I passed the audience the onload function did not catch any credentials.

The easiest way to reproduce this issue is to pass the audience when you try to login.

Widcket commented 1 year ago

If the Auth0 application is configured as described, I'm unable to reproduce on the sample app:

https://github.com/auth0/auth0-flutter/assets/5055789/5a9b6f94-7f9e-4ba9-98b2-cec9c63ddce0

(note I'm passing an audience value)

ranjitIN commented 1 year ago

i configured everything as per the sample app. and the audience i created for that using signing algorithm HS256 below i am attaching my code. please let me know if i am doing anything wrong.

https://github.com/auth0/auth0-flutter/assets/78366707/e080c658-0bde-4725-b923-3180e641bf96

import 'package:auth0_flutter/auth0_flutter.dart';
import 'package:auth0_flutter/auth0_flutter_web.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'constants.dart';
import 'hero.dart';
import 'user.dart';

class ExampleApp extends StatefulWidget {
  final Auth0? auth0;
  const ExampleApp({this.auth0, final Key? key}) : super(key: key);

  @override
  State<ExampleApp> createState() => _ExampleAppState();
}

class _ExampleAppState extends State<ExampleApp> {
  UserProfile? _user;

  late Auth0 auth0;
  late Auth0Web auth0Web;

  @override
  void initState() {
    super.initState();
    auth0 = widget.auth0 ?? Auth0(auth0Domain, clientId);
    auth0Web = Auth0Web(auth0Domain, clientId);

    if (kIsWeb) {
      auth0Web.onLoad().then((final credentials) => setState(() {
            print("access token ${credentials?.accessToken}");
            _user = credentials?.user;
          }));
    }
  }

  Future<void> login() async {
    try {
      if (kIsWeb) {
        return auth0Web.loginWithRedirect(
          audience: audience,
          redirectUrl: 'http://localhost:3000',
        );
      }

      var credentials = await auth0.webAuthentication().login();

      setState(() {
        _user = credentials.user;
      });
    } catch (e) {
      print(e);
    }
  }

  Future<void> logout() async {
    try {
      if (kIsWeb) {
        await auth0Web.logout(returnToUrl: 'http://localhost:3000');
      } else {
        await auth0.webAuthentication().logout();
        setState(() {
          _user = null;
        });
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(final BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Padding(
        padding: const EdgeInsets.only(
          top: padding,
          bottom: padding,
          left: padding / 2,
          right: padding / 2,
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
          Expanded(
              child: Row(children: [
            _user != null
                ? Expanded(child: UserWidget(user: _user))
                : const Expanded(child: HeroWidget())
          ])),
          _user != null
              ? ElevatedButton(
                  onPressed: logout,
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all<Color>(Colors.black),
                  ),
                  child: const Text('Logout'),
                )
              : ElevatedButton(
                  onPressed: login,
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all<Color>(Colors.black),
                  ),
                  child: const Text('Login'),
                )
        ]),
      )),
    );
  }
}
ranjitIN commented 1 year ago

is there any update on this

Widcket commented 1 year ago

@ranjitIN you can't use HS256 with a mobile app, because it's a symmetric algorithm, meaning it requires a secret on both sides; but mobile apps are public clients, not confidential clients. You need to use an an asymmetric algorithm, like RS256.

ranjitIN commented 1 year ago

I also tried with RS256 it's not working

Widcket commented 1 year ago

@ranjitIN if you open the developer tools, can you spot any errors coming back from the login page (on the "Networking" tab)?

ranjitIN commented 1 year ago

Yup There are some errors.

alvaradolabs.auth0.com/authorize?
 Failed to load resource: the server responded with a status of 400 ()

after some time in flutter console

ChromeProxyService: Failed to evaluate expression 'credentials': InternalError: Expression evaluation in async frames is not supported. No frame with index 78.. Error: TIMEOUT: Timeout

dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 288:49  throw_
packages/auth0_flutter/src/web/auth0_flutter_plugin_real.dart 128:7           credentials$
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 60:31            <fn>
dart-sdk/lib/async/zone.dart 1666:54                                          runBinary
dart-sdk/lib/async/future_impl.dart 162:22                                    handleError
dart-sdk/lib/async/future_impl.dart 796:46                                    handleError
dart-sdk/lib/async/future_impl.dart 817:13                                    _propagateToListeners
dart-sdk/lib/async/future_impl.dart 592:5                                     [_completeError]
dart-sdk/lib/async/future_impl.dart 683:7                                     callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 177:15           <fn>

https://github.com/auth0/auth0-flutter/assets/78366707/89122093-30b0-4491-8473-6815baf3c65b

Widcket commented 1 year ago

Thanks for the information. Could you please include the error response from the Dev Tools "Network" tab?

ranjitIN commented 1 year ago

Thanks for the support the issue is resolved after adding my web URL in allowed web origins. when is see the but its not throwing any exception. image

if anyone facing similar issue in adding your web url on Allowed web origins solve my problem

image

ranjitIN commented 1 year ago

thanks for the support but i am facing refresh token web iam using loginWithPopup on flutter web but not able to fetch the refresh token is there anything i need to pass

  credentials = await auth0.loginWithPopup(
            audience: audience,
            scopes: {'openid', 'profile', 'email', 'offline_access'});

image

please let me know am i doing anything wrong

Widcket commented 1 year ago

@ranjitIN we use GitHub issues for bug reports and feature requests only. For help with usage, please raise a support ticket or refer to the community forums.