具有基本身份验证的Flutter WebView

时间:2019-05-09 15:18:59

标签: webview flutter basic-authentication

我正在加载网页,我想使用基本身份验证登录,我有使用Swift的经验,能够进行如下所示的基本身份验证,但是我无法为我的应用的Flutter版本实现基本身份验证。

---- Swift代码---

func configureView() {
        let username = "user"
        let password = "pass"
        let userPasswordString = "\(user):\(pass)"
        let userPasswordData = userPasswordString.data(using: String.Encoding.utf8)
        let base64EncodedCredential = userPasswordData!.base64EncodedString(options:[])
        let authString = "Basic \(base64EncodedCredential)"
        let url = URL(string: "http://myurl")
        var request = URLRequest(url: url!)
        request.setValue(authString, forHTTPHeaderField: "Authorization")
        webView.scalesPageToFit = true
        webView.loadRequest(request)
    }

--- Flutter WebView --->使用URL加载Webview

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

class AddShipment extends StatefulWidget {

  final String url;

  AddShipment(this.url);

  @override 
  State<StatefulWidget> createState() {
    return new _AddShipment();
  }
}

class _AddShipment extends State<AddShipment> {
  final flutterWebviewPlugin = new FlutterWebviewPlugin();

  @override
  void initState() {
    super.initState();

    flutterWebviewPlugin.close();
  }

  @override
  void dispose() {

    flutterWebviewPlugin.dispose();

    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return new WebviewScaffold(
      appBar: new AppBar(
          title: new Text("WebView"),
          centerTitle: true,
          backgroundColor: Colors.blue[900],
          elevation: 0.0,
      ),
      url: widget.url,
      withJavascript: true,
    );
  }
}

创建urlRequest的正确方法是什么?我尝试过:

static Future<Response> getURL(
      final String username, final String password) {
    final String url = 'http://myurl';
    final String auth =
        'Basic ' + base64Encode(utf8.encode('$username:$password'));
    return http.get(url, headers: {'Authorization': auth});
}

2 个答案:

答案 0 :(得分:1)

您还可以尝试使用我的插件flutter_inappbrowser编辑:它已重命名为flutter_inappwebview)。

下面显示了在Authorization: Basic ...属性中使用initialHeaders标头的示例:

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: InAppWebViewPage()
    );
  }
}

class InAppWebViewPage extends StatefulWidget {
  @override
  _InAppWebViewPageState createState() => new _InAppWebViewPageState();
}

class _InAppWebViewPageState extends State<InAppWebViewPage> {
  InAppWebViewController webView;
  String username = "USERNAME";
  String password = "PASSWORD";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("InAppWebView")
      ),
      body: Container(
          child: Column(children: <Widget>[
            Expanded(
              child: Container(
                child: InAppWebView(
                  initialUrl: "http://myurl",
                  initialHeaders: {
                    'Authorization': 'Basic ' + base64Encode(utf8.encode('$username:$password'))
                  },
                  initialOptions: InAppWebViewWidgetOptions(
                      inAppWebViewOptions: InAppWebViewOptions(
                        debuggingEnabled: true,
                      )
                  ),
                  onWebViewCreated: (InAppWebViewController controller) {
                    webView = controller;
                  },
                  onLoadStart: (InAppWebViewController controller, String url) {

                  },
                  onLoadStop: (InAppWebViewController controller, String url) {

                  },
                ),
              ),
            ),
          ]))
    );
  }
}

这是使用onReceivedHttpAuthRequest事件的示例:

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';

Future main() async {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: InAppWebViewPage()
    );
  }
}

class InAppWebViewPage extends StatefulWidget {
  @override
  _InAppWebViewPageState createState() => new _InAppWebViewPageState();
}

class _InAppWebViewPageState extends State<InAppWebViewPage> {
  InAppWebViewController webView;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("InAppWebView")
      ),
      body: Container(
          child: Column(children: <Widget>[
            Expanded(
              child: Container(
                child: InAppWebView(
                  initialUrl: "http://myurl",
                  initialOptions: InAppWebViewWidgetOptions(
                      inAppWebViewOptions: InAppWebViewOptions(
                        debuggingEnabled: true,
                      )
                  ),
                  onWebViewCreated: (InAppWebViewController controller) {
                    webView = controller;
                  },
                  onLoadStart: (InAppWebViewController controller, String url) {

                  },
                  onLoadStop: (InAppWebViewController controller, String url) {

                  },
                  onReceivedHttpAuthRequest: (InAppWebViewController controller, HttpAuthChallenge challenge) async {
                    return HttpAuthResponse(username: "USERNAME", password: "PASSWORD", action: HttpAuthResponseAction.PROCEED);
                  },
                ),
              ),
            ),
          ]))
    );
  }
}

答案 1 :(得分:0)

Add your additional headers to the WebviewScaffold constructor.

    url: widget.url,
    withJavascript: true,
    headers: {'Authorization': 'Basic ' + base64Encode(utf8.encode('$widget.username:$widget.password'))},

Pass username and password into the widget, in the same way that you are passing the url.