Search code examples
flutterory

ORY on flutter android/ios


I am trying to use ORY Login in my android/ios app. Did not find any example on the web, started from the web one, but does not work. This is what I tried:

import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:ory_client/ory_client.dart';

class AuthService {
  final FrontendApi _ory;
  Session? _identity;

  AuthService(Dio dio) : _ory = OryClient(dio: dio).getFrontendApi();

  static AuthService init() {
    const baseUrl = "https://{my.slug}.projects.oryapis.com";

    // create the dio client for http requests
    final options = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: 10000,
      receiveTimeout: 5000,
      headers: {
        "Accept": "application/json",
      },
      validateStatus: (status) {
        // here we prevent the request from throwing an error when the status code is less than 500 (internal server error)
        return status! < 500;
      },
    );
    final dio = DioForNative(options);
    // final adapter = BrowserHttpClientAdapter();
    // enable cookies support
    // we need this so we can send HTTP requests to the server with the cookies stored in the browser
    // adapter.withCredentials = true;
    // dio.httpClientAdapter = adapter;

    return AuthService(dio);
  }

  Future<bool> isAuthenticated() async {
    try {
      final resp = await _ory.toSession();
      if (resp.statusCode == 200) {
        _identity = resp.data;
        return true;
      }
      return false;
    } catch (error) {
      log(error.toString());
      return false;
    }
  }

  Future login() async {
    try {
      final resp = await _ory.createNativeLoginFlow();
      log(resp.toString());
      final sdf = await _ory.updateLoginFlow(
        flow: "login", updateLoginFlowBody: UpdateLoginFlowBody());
      log(sdf.toString());
    } catch (error) {
      log(error.toString());
    }
  }

  Future logout() async {
    try {
      final resp = await _ory.performNativeLogout(
          performNativeLogoutBody: PerformNativeLogoutBody());
      final sdf = await _ory.updateLogoutFlow(token: "resp.data!.logoutToken TODO");
      log(resp.toString());
      log(sdf.toString());
    } catch (error) {
      log(error.toString());
    }
  }

  Session? get identity => _identity;
}

I get a DeseralizationError on await _ory.createNativeLoginFlow(). Does somebody have a working example?


Solution

  • I figured out that replacing final dio = DioForNative(options) with final dio = Dio(options) does not throw that error.