4

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

2 Answers 2

6

You can also try my plugin flutter_inappbrowser (EDIT: it has been renamed to flutter_inappwebview).

An example using the Authorization: Basic ... header in the initialHeaders attribute is presented below:

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) {

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

Instead, this is an example using the onReceivedHttpAuthRequest event:

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);
                  },
                ),
              ),
            ),
          ]))
    );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

In the first example you, could you instead use a bearer access token and have the user authenticated?
3

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.

1 Comment

it's not working for me. I don't know why? I want to login directly to website through url request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.