LoginSignup
7
7

More than 3 years have passed since last update.

FlutterのWebViewからBasic認証ページにアクセスする

Last updated at Posted at 2020-02-16

概要

FlutterアプリのWebViewからBasic認証ページの接続テストをする際に少しハマったのでメモ。
WebViewパッケージはflutter_webview_pluginを使用。

pubspec.yaml
dependencies:
  flutter_webview_plugin: ^0.3.10+1
$ flutter pub get

ローカルサーバー立ててlocalhostにBasic認証接続してみた。
Node.js + Express + passport.jsでローカルサーバーにBasic認証ページを立てる - Qiita

サンプルアプリ

ヘッダー情報にAuthorizationを指定することでBasic認証が通せる。ユーザー名とパスワードを連結した上でbase64Encodeが必要な点に注意。

main.dart
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'dart:convert';
import 'dart:io';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       routes: {
        "/": (_) => new WebviewScaffold(
          url: getLocalhostUrl(),
          headers: {
            'Authorization':'Basic ' + base64Encode(utf8.encode('user:pass')) 
          },
          appBar: new AppBar(
            title: new Text("Basic authentication"),
          ),
        ),
      },
    );
  }

  String getLocalhostUrl() {
    if (Platform.isIOS) {
      return "http://127.0.0.1:3000/";
    } else if (Platform.isAndroid) {
      return "http://10.0.2.2:3000/";
    } else {
      return "http://localhost:3000/";
    }
  }
}

iOS SimulatorとAndoroid Emulatorで動作確認できました。

スクリーンショット 2020-02-16 18.32.11.png

ハマった点

接続先がlocalhost、およびhttpであることが原因で以下3点ハマった。

  • iOS Simulatorで認証ページが真っ白になる
  • Andoroid EmulatorでERR_CREARTEXT_NOT_PERMITTEDが出る
  • Andoroid EmulatorでERR_CONNECTION_REFUSEDが出る

解決法

それぞれ記事書いたので、同様の現象に悩まれている方はご参照ください。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7