How to implement Internet Identity authentication with FLUTTER application?

120 Views Asked by At

I am unable to navigate back to my application after successfull log in.

Package: https://pub.dev/documentation/agent_dart/latest/

Example project I am trying to run: https://github.com/AstroxNetwork/agent_dart_examples/tree/main/auth_counter

Middle page repository: https://github.com/krpeacock/auth-client-demo

After login I am unable to navigate back to the app automatically. And when I manually navigate it shows the below error.

Got error: PlatformException(CANCELED, User canceled login, null, null)

I am using ngrok for connection with my application.

My main.dart

import 'package:agent_dart/agent_dart.dart';
import 'package:agent_dart_auth/agent_dart_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uni_links/uni_links.dart';
import 'dart:async';

// import Counter class with canister call
import 'counter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool _loading = false;
  String? _error;
  String? _status;
  // setup state class variable;
  Counter? counter;
  Identity? _identity;

  StreamSubscription? _sub;

  @override
  void initState() {
    super.initState();
    initCounter();
    initUniLinks();
  }

  @override
  void dispose() {
    _sub?.cancel();
    super.dispose();
  }

  void initUniLinks() async {
    // Attach a listener to the links stream
    _sub = linkStream.listen((String? link) {
      if (link != null) {
        // Handle the deep link, e.g., parse and use its data
        print("Deep link: $link");
        // You can add your navigation logic here
      }
    }, onError: (err) {
      // Handle errors
      print("Failed to handle deep link: $err");
    });

    // Handle initial link if the app was opened with a deep link
    try {
      String? initialLink = await getInitialLink();
      if (initialLink != null) {
        print("Initial deep link: $initialLink");
        // You can add your navigation logic here
      }
    } catch (e) {
      // Handle errors
      print("Failed to handle initial deep link: $e");
    }
  }


  Future<void> initCounter({Identity? identity}) async {
    // initialize counter, change canister id here
    counter = Counter(
        canisterId: 'bkyz2-fmaaa-aaaaa-qaaaq-cai',
        url: 'https://abde-2401-4900-1c35-870c-ccd1-a875-346-c71b.ngrok-free.app');
    // set agent when other paramater comes in like new Identity
    await counter?.setAgent(newIdentity: identity);
    isAnon();
    await getValue();
  }

  void isAnon() {
    if (_identity == null || _identity!.getPrincipal().isAnonymous()) {
      setState(() {
        _status = 'You have not logined';
      });
    } else {
      setState(() {
        _status = 'Login principal is :${_identity!.getPrincipal().toText()}';
      });
    }
  }

  // get value from canister
  Future<void> getValue() async {
    var counterValue = await counter?.getValue();
    setState(() {
      _error = null;
      _counter = counterValue ?? _counter;
      _loading = false;
    });
  }

  // increment counter
  Future<void> _incrementCounter() async {
    setState(() {
      _loading = true;
    });
    try {
      await counter?.increment();
      await getValue();
    } catch (e) {
      setState(() {
        _error = e.toString();
        _loading = false;
      });
    }
  }

  Future<void> authenticate() async {
    try {
      var authClient = WebAuthProvider(
          scheme: "identity",
          path: 'auth',
          authUri:
          Uri.parse('https://1de7-2401-4900-1c35-870c-ccd1-a875-346-c71b.ngrok-free.app'),
          useLocalPage: true);

      await authClient.login(
        // AuthClientLoginOptions()..canisterId = "rdmx6-jaaaa-aaaaa-aaadq-cai"
      );
      // var loginResult = await authClient.isAuthenticated();

      _identity = authClient.getIdentity();
      await counter?.setAgent(newIdentity: _identity);
      isAnon();
    } on PlatformException catch (e) {
      setState(() {
        _status = 'Got error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    var logginButton =
    (_identity == null || _identity!.getPrincipal().isAnonymous())
        ? MaterialButton(
      onPressed: () async {
        await authenticate();
      },
      child: Text('Login Button'),
    )
        : SizedBox.shrink();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _status ?? '',
            ),
            Text(
              _error ?? 'The canister counter is now:',
            ),
            Text(
              _loading ? 'loading...' : '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            logginButton
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Logged In page of middle page application

import { ActorSubclass } from "@dfinity/agent";
import { AuthClient } from "@dfinity/auth-client";
import { html, render } from "lit-html";
import { renderIndex } from ".";
import { _SERVICE } from "../../../declarations/whoami/whoami.did";

const content = () => html`<div class="container">
  <style>
    #whoami {
      border: 1px solid #1a1a1a;
      margin-bottom: 1rem;
    }
  </style>
  <h1>Internet Identity Client</h1>
  <h2>You are authenticated!</h2>
  <p>To see how a canister views you, click this button!</p>
  <button type="button" id="whoamiButton" class="primary">Who am I?</button>
  <input type="text" readonly id="whoami" placeholder="your Identity" />
  <button id="logout">log out</button>
  <button id="redirectToApp">Back to App</button>
</div>`;

export const renderLoggedIn = (
  actor: ActorSubclass<_SERVICE>,
  authClient: AuthClient
) => {
  render(content(), document.getElementById("pageContent") as HTMLElement);

  (document.getElementById("whoamiButton") as HTMLButtonElement).onclick =
    async () => {
      try {
        const response = await actor.whoami();
        (document.getElementById("whoami") as HTMLInputElement).value =
          response.toString();
      } catch (error) {
        console.error(error);
      }
    };

  (document.getElementById("logout") as HTMLButtonElement).onclick =
    async () => {
      await authClient.logout();
      renderIndex(authClient);
    };

    (document.getElementById("redirectToApp") as HTMLButtonElement).onclick =
    () => {
      window.location.href = 'myapp://callback';
    };
};

AndroidManifest.XML

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.auth_counter">
   <application
        android:label="auth_counter"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize"
            android:exported="true">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
                <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" android:host="callback"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

I tried using Internet Identity for mainnet as well as local, but nothing worked.

Checked the package code , everything seems fine.

I feel like I am missing something.

If someone can help me it would be a great help :)

0

There are 0 best solutions below