Xamarin.Forms中的网页视图认证,在导航到新页面(Shell)时需要重新进行认证吗?

4

我在一个Shell Xamarin.Forms应用中有一个Webview。我请求了一个安全网页并被转到我的公司SSO(单点登录),我通过了验证并可以看到安全内容。

这个Webview:

<WebView x:Name="web1" HorizontalOptions="CenterAndExpand"
                 VerticalOptions="FillAndExpand" HeightRequest="1000" WidthRequest="1000"/>

当我从主菜单或通过在列表视图中点击项目(例如,想象一下RSS头条新闻列表,点击以阅读文章)跳转到一个新的Shell页面时,该页面上有一个几乎相同的WebView标签,在页面构造函数或覆盖OnAppearing方法时将Source设置为安全页面,预期会话/cookie仍处于活动状态,但实际上我会被重定向回登录页面。

是否有任何方法可以确保我的应用程序中的所有Webviews (iOS和Android)使用相同的会话,以便用户只需登录一次?

我尝试在app.xaml.cs文件中创建了一个webview,并使用Content.Children.Add(App.Web1)将其添加到我的页面中,我简单地认为这意味着我在所有页面上都使用相同的webview,因此也使用相同的会话!但似乎也不起作用。

非常感谢任何和所有的帮助。

谢谢。


您可以尝试通过在本地项目中创建Webview的自定义渲染器来设置会话/cookie。请参阅以下线程以获取更多详细信息:Xamarin WebView Cookie to seamlessly authenticate user without re-entering credentialsSetting Cookies in a WebView - nevermore
尝试过这个。在新的Webview中移除cookie之前,我已经检查过它们,发现那些认证cookie已经存在了!(仍然无法工作)-然后我将它们删除,加入我以前成功调用时获得的新cookie,但仍然被转发到登录服务。 - Chris M
1个回答

0

使用cookieJs与常规的cookie插入方法结合,可以解决在前端设置cookie的问题:

CookieJs:

!function(e){var n;if("function"==typeof define&&define.amd&&(define(e),n=!0),"object"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if("undefined"!=typeof document){"number"==typeof(i=e({path:"/"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():"";try{var c=JSON.stringify(t);/^[{[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var f="";for(var u in i)i[u]&&(f+="; "+u,!0!==i[u]&&(f+="="+i[u].split(";")[0]));return document.cookie=n+"="+t+f}}function c(e,t){if("undefined"!=typeof document){for(var r={},i=document.cookie?document.cookie.split("; "):[],c=0;c<i.length;c++){var f=i[c].split("="),u=f.slice(1).join("=");t||'"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,"",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});

示例:

iOS 渲染器:

public class DefaultWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>, IWKScriptMessageHandler, IWKNavigationDelegate
    {
        const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";        
        const string cookieJs = "!function(e){var n;if(\"function\"==typeof define&&define.amd&&(define(e),n=!0),\"object\"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if(\"undefined\"!=typeof document){\"number\"==typeof(i=e({path:\"/\"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():\"\";try{var c=JSON.stringify(t);/^[\\{\\[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\\(\\)]/g,escape);var f=\"\";for(var u in i)i[u]&&(f+=\"; \"+u,!0!==i[u]&&(f+=\"=\"+i[u].split(\";\")[0]));return document.cookie=n+\"=\"+t+f}}function c(e,t){if(\"undefined\"!=typeof document){for(var r={},i=document.cookie?document.cookie.split(\"; \"):[],c=0;c<i.length;c++){var f=i[c].split(\"=\"),u=f.slice(1).join(\"=\");t||'\"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,\"\",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});";
        WKUserContentController userController;
        public DefaultWebViewRenderer()
        {

        }
        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);
            if (Control == null && e.OldElement == null)
            {
                userController = new WKUserContentController();
                var cookieValue = string.Empty; //Whatever you want
                var jsScript = new WKUserScript(new NSString(cookieJs), WKUserScriptInjectionTime.AtDocumentStart, false);
                var yourCookie = new WKUserScript(new NSString("Cookies.set('CookieKey','" + cookieValue + "',{expires : 30, domain : '.yourdomain.com' })"), WKUserScriptInjectionTime.AtDocumentStart, false);                  
                userController.AddUserScript(jsScript);
                userController.AddUserScript(yourCookie);                    
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                userController.AddUserScript(script);
                userController.AddScriptMessageHandler(this, "invokeAction");
                var config = new WKWebViewConfiguration { UserContentController = userController };
                var webView = new WKWebView(Frame, config);

                SetNativeControl(webView);
            }
            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("invokeAction");
            }
            if (e.NewElement != null)
            {
                if (Element.Source is UrlWebViewSource urlSource)
                {
                    var url = new NSUrl(urlSource.Url);
                    var storage = NSHttpCookieStorage.SharedStorage;
                    storage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
                    var request = new NSMutableUrlRequest(url);
                    Control.LoadRequest(request);
                }
                else if (Element.Source is HtmlWebViewSource htmlSource)
                {
                    Control.LoadHtmlString(htmlSource.Html, null);
                }
            }
        }

        public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
        {
            Element.JavascriptBridgeInvoked(message.Body.ToString());
        }
    }

Android 渲染器:

public class DefaultWebViewRenderer : WebViewRenderer
{
    const string JavaScriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";
    public DefaultWebViewRenderer(Context context) : base(context)
    {
    }
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
    {
        base.OnElementChanged(e);
        if (Control != null && e.NewElement is CustomWebView webView)
        {
            Control.SetWebViewClient(new WebViewTestClient());
            Control.ClearSslPreferences();
            Control.Settings.SetAppCacheEnabled(false); 
            Control.Settings.DatabaseEnabled = true;
            Control.Settings.DomStorageEnabled = true;
            Control.Settings.AllowFileAccessFromFileURLs = true;
            Control.Settings.AllowUniversalAccessFromFileURLs = true;
            Control.Settings.CacheMode = Android.Webkit.CacheModes.NoCache;                
            Control.Settings.AllowContentAccess = true;
            Control.Settings.AllowFileAccess = true;
            Control.Settings.JavaScriptEnabled = true;
            Control.Settings.JavaScriptCanOpenWindowsAutomatically = true;
            var cookieManager = CookieManager.Instance;
            cookieManager.SetAcceptCookie(true);
            cookieManager.SetAcceptThirdPartyCookies(Control, true);
            try
            {
                Control.SetDownloadListener(new DownloadListener());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            if (e.OldElement != null)
            {
                Control.RemoveJavascriptInterface("jsBridge");
            }
            Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
            InjectJS(JavaScriptFunction);
            if (webView.Source is UrlWebViewSource webSource)
            {
                Control.LoadUrl(webSource.Url);
            }
        }
    }

    private void InjectJS(string script)
    {
        if (Control != null)
        {
            Control.LoadUrl(string.Format("javascript: {0}", script));
        }
    }
}
public class WebViewTestClient : WebViewClient
{
    public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)
    {
         var cookieJs = "!function(e){var n;if(\"function\"==typeof define&&define.amd&&(define(e),n=!0),\"object\"==typeof exports&&(module.exports=e(),n=!0),!n){var t=window.Cookies,o=window.Cookies=e();o.noConflict=function(){return window.Cookies=t,o}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if(\"undefined\"!=typeof document){\"number\"==typeof(i=e({path:\"/\"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():\"\";try{var c=JSON.stringify(t);/^[\\{\\[]/.test(c)&&(t=c)}catch(e){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\\(\\)]/g,escape);var f=\"\";for(var u in i)i[u]&&(f+=\"; \"+u,!0!==i[u]&&(f+=\"=\"+i[u].split(\";\")[0]));return document.cookie=n+\"=\"+t+f}}function c(e,t){if(\"undefined\"!=typeof document){for(var r={},i=document.cookie?document.cookie.split(\"; \"):[],c=0;c<i.length;c++){var f=i[c].split(\"=\"),u=f.slice(1).join(\"=\");t||'\"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(e){}if(r[a]=u,e===a)break}catch(e){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,\"\",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});";
        var cookieValue = string.Empty; //Whatever you want
        view.EvaluateJavascript(cookieJs, null);
        view.EvaluateJavascript("Cookies.set('CookieKey','" + cookieValue + "',{expires : 30, domain : '.yourdomain.com' })", null);
        base.OnPageStarted(view, url, favicon);
        view.ClearCache(true);
    }
    public override void OnPageFinished(Android.Webkit.WebView view, string url)
    {
        base.OnPageFinished(view, url);
        view.ClearCache(true);
    }
    public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
    {
        handler.Proceed();
        base.OnReceivedSslError(view, handler, error);
    }
}
public class DownloadListener : Java.Lang.Object, Android.Webkit.IDownloadListener
{
    public DownloadListener()
    {
    }
    public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
    {
        if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out _))
            return;
        try
        {
            if (HasPermissions())
            {
                Android.Net.Uri contentUri = Android.Net.Uri.Parse(url);
                DownloadManager.Request request = new DownloadManager.Request(contentUri);
                request.SetMimeType(mimetype);
                var cookies = Android.Webkit.CookieManager.Instance.GetCookie(url);
                request.AddRequestHeader("cookie", cookies);
                request.AddRequestHeader("User-Agent", userAgent);
                request.SetDescription("Downloading file...");
                request.SetTitle(Android.Webkit.URLUtil.GuessFileName(url, contentDisposition, mimetype));
                request.AllowScanningByMediaScanner();
                request.SetNotificationVisibility(Android.App.DownloadVisibility.VisibleNotifyCompleted);
                request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, ".pdf");
                Android.App.DownloadManager dm = (Android.App.DownloadManager)CrossCurrentActivity.Current.Activity.GetSystemService(Android.Content.Context.DownloadService);
                dm.Enqueue(request);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    private static bool HasPermissions()
    {
        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
        {
            string[] WriteLocation =
            {
                Android.Manifest.Permission.WriteExternalStorage,
                Android.Manifest.Permission.ReadExternalStorage
            };
            var perm = CrossCurrentActivity.Current.AppContext.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage);
            if (perm != (int)Android.Content.PM.Permission.Granted)
            {
                CrossCurrentActivity.Current.Activity.RequestPermissions(WriteLocation, 2);
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return true;
        }
    }
}
public class JSBridge : Java.Lang.Object
{
    private readonly WeakReference<DefaultWebViewRenderer> hybridWebViewRenderer;
    public JSBridge(DefaultWebViewRenderer hybridRenderer)
    {
        hybridWebViewRenderer = new WeakReference<DefaultWebViewRenderer>(hybridRenderer);
    }
    [JavascriptInterface]
    [Export("invokeAction")]
    public void InvokeAction(string data)
    {
        if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out DefaultWebViewRenderer hybridRenderer) && hybridRenderer != null && hybridRenderer.Element is CustomWebView webView)
        {
            webView.JavascriptBridgeInvoked(data);
        }
    }
}

我无法在前端设置 HttpOnly cookies,这可能与 Xamarin.Forms 4.5 更新有关,该更新删除了 WebViewRenderer 并替换为 WKWebViewRenderer...值得调查。 - Chris M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接