Search code examples
webviewflutterbasic-authentication

Flutter WebView with Basic Authentication


I am loading a web page and I want to login with Basic Authentication, I have experience with Swift and able to do Basic Auth like below but I couldn't implement Basic Auth for Flutter version of my app.

---- Swift Code ---

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 ---> load webview with URL

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,
    );
  }
}

What is the correct way to create an urlRequest? I tried:

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});
}

Solution

  • 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.