Home > Software engineering >  Pass auth cookie to WebView - Flutter
Pass auth cookie to WebView - Flutter

Time:09-21

I'm building a WebView based app.
Authenticating occurs inside the app without using webview. I'm making a request to server and getting a session token from auth cookie.
When user passes authentication page the app pushes him to the main page. There are some buttons that leads to the WebView.

The problem is that I need to pass my auth cookie to the WebView.

However when WebView appears it immediately redirects me to web app authentication page instead of catalog page. But I need catalog page.

I used enter image description here But when I'm trying to reproduce the same request in postman, I get a status code 200. I'm passing a valid token throw auth_cookie.
enter image description here Is this a problem?

CodePudding user response:

It is it not easy doing it it with flutter_webview but would be way easier with the flutter_webview_plugin.

Here's an example

class Web extends StatefulWidget {
  final Map<String, dynamic> cookie;

  Web(this.cookie);

  @override
  _WebState createState() => _WebState();
}

class _WebState extends State<Web> {
  final webPlugin = FlutterWebviewPlugin();

  @override
  void initState() {
    super.initState();
    webPlugin.onUrlChanged.listen((event) async {
      final cookies = await webPlugin.getCookies();
    });
    webPlugin.onStateChanged.listen((event) async {
      if (mounted) {
        final cookies = await webPlugin.getCookies();
        switch (event.type) {
          case WebViewState.shouldStart:
            {
              print(event.type);
            }
            break;
          case WebViewState.abortLoad:
            {
              print(event.type);
            }
            break;
          case WebViewState.startLoad:
            {
              print(event.type);
            }
            break;
          case WebViewState.finishLoad:
            {
              print(event.type);
            }
            break;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelProvider<WebViewViewModel>.withConsumer(
      viewModelBuilder: () => WebViewViewModel(),
      builder: (context, model, _) {
        return SafeArea(
          child: WebviewScaffold(
            appBar: AppBar(
              backgroundColor: apex,
              actions: [IconButton(
                  icon: Icon(Icons.replay, color: Colors.white, size: 28,), onPressed: () => webPlugin.reload()),],
            ),
            clearCookies: true,
            resizeToAvoidBottomInset: true,
            headers: this.widget.cookie,
            url: "your url",
            withJavascript: true,
            withLocalStorage: true,
            withZoom: false,
            supportMultipleWindows: true,
            allowFileURLs: true,
          ),
        );
      },
    );
  }
  @override
  void dispose() {
    webPlugin.dispose();
    super.dispose();
  }
}

CodePudding user response:

Finally I found a solution!

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';

import 'package:skin_technology/core/session_data/repo/session_data_service.dart';
import 'package:webview_cookie_manager/webview_cookie_manager.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewScreen extends StatelessWidget {
  WebViewScreen({Key? key, required this.url}) : super(key: key);

  final String url;
  WebViewController? webController;

  final cookieManager = WebviewCookieManager();

  Future<String?> _getToken() async {
    final token = (await SessionDataService.sessionData)?.token;
    if (token == null) return null;
    return token;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.transparent,
        ),
        body: Stack(
          children: [
            Container(
              color: Colors.amber,
            ),
            SafeArea(
              bottom: false,
              child: FutureBuilder<String?>(
                  future: _getToken(),
                  builder:
                      (BuildContext context, AsyncSnapshot<String?> snapshot) {
                    if (snapshot.hasData) {
                      final token = snapshot.data;
                      if (token == null) return Container();

                      return WebView(
                        javascriptMode: JavascriptMode.unrestricted,
                        initialUrl: url,
                        onWebViewCreated: (controller) {
                          cookieManager.setCookies([
                            Cookie('auth', token)
                              ..domain = 'clubskt.ru'
                              ..httpOnly = false,
                          ]);
                          webController = controller;
                        },
                      );
                    }
                    return Container();
                  }),
            ),
          ],
        ));
  }
}
  • Related