Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth0-How to use with Flutter

I need use Auth0 with Flutter but there is no such SDK in Auth0 site.

Auth0 works to create such SDK for Flutter.

Did anyone use Auth0 with Flutter or what can you advise?

like image 820
Vahe Ghevondyan Avatar asked Oct 31 '18 05:10

Vahe Ghevondyan


People also ask

How do you use tokens in flutter?

You can generate tokens on the server by creating a Server Client and then using the Create Token method. If generating a token to use client side, the token must include the userID claim in the token payload, where as server tokens do not.


1 Answers

Its very simple to get started with flutter auth0

Have a class for auth0 and call this at the places you need them. But also be sure to set the constants AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_REDIRECT_URI, AUTH0_ISSUER

class Auth0 {

  final FlutterAppAuth appAuth = FlutterAppAuth();

  Map<String, Object> parseIdToken(String idToken) {
    final List<String> parts = idToken.split('.');
    assert(parts.length == 3);
    return jsonDecode(
        utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))));
  }

  Future<Map<String, Object>> getUserDetails(String accessToken) async {
    const String url = 'https://$AUTH0_DOMAIN/userinfo';
    final http.Response response = await http.get(
      url,
      headers: <String, String>{'Authorization': 'Bearer $accessToken'},
    );
    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception('Failed to get user details');
    }
  }

  Future<void> loginAction() async {
      isBusy = true;
      errorMessage = 'Error! - ';

    try {
      final AuthorizationTokenResponse result =
          await appAuth.authorizeAndExchangeCode(
        AuthorizationTokenRequest(
          AUTH0_CLIENT_ID,
          AUTH0_REDIRECT_URI,
          issuer: 'https://$AUTH0_DOMAIN',
          scopes: <String>['openid', 'email', 'profile', 'offline_access'],
          promptValues: ['login']
        ),
      );

      final Map<String, Object> idToken = parseIdToken(result.idToken);
      final Map<String, Object> profile =
          await getUserDetails(result.accessToken);


        isBusy = false;
        name = idToken['name'];
        email = profile['email'];
        picture = profile['picture'];


    } on Exception catch (e, s) {
      print('login error: $e - stack: $s');

        isBusy = false;
        errorMessage = e.toString();
    }
  }

Instead of using a boolean for checking isLoggedIn try saving the token in the localstorage and that will set the state as is.

like image 148
Mohamed Haris Avatar answered Sep 22 '22 16:09

Mohamed Haris