使用 CEFSharp 的 HTTP 基本身份验证

问题描述 投票:0回答:1

程序的任务是,当应用程序打开时,会自动登录站点,要求 HTTP 身份验证,前提是预先输入登录名、密码和 URL。

我尝试使用这种方法在地址栏中嵌入登录名和密码:

if (auth.URL.Contains(@"http://") || auth.URL.Contains(@"http:\\"))
{
    auth.URL = $"http://{auth.Login}:{auth.Password}@{auth.URL.Remove(0, 7)}/";
}
else if (auth.URL.Contains(@"https://") || auth.URL.Contains(@"https:\\"))
{
    auth.URL = $"https://{auth.Login}:{auth.Password}@{auth.URL.Remove(0, 8)}/";
}
else
{
    auth.URL = $"http://{auth.Login}:{auth.Password}@{auth.URL}/";
}

但是我注意到,如果我将测试登录“ENTERPRISE\A.Example”和密码“#Mdm256$”粘贴到地址栏中,网站无法正常打开。我发现这是因为 \ 和 # 符号。我还尝试使用

MyRequestHandler
方法编写自定义
GetAuthCredentials()
类:

protected override bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
    callback.Continue(username, password);
    return true;
}

但是它没有在代码中调用或使用,也没有任何关于如何调用它的信息

c# windows cefsharp
1个回答
0
投票

您需要将自定义

RequestHandler
实例分配给
ChromiumWebBrowser.RequestHandler
属性,如下所示:

browser.RequestHandler = new CustomRequestHandler();

public class CustomRequestHandler : CefSharp.Handler.RequestHandler
{
    protected override bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
    {
        //Cast IWebBrowser to ChormiumWebBrowser if you need to access the UI control
        //You can Invoke onto the UI Thread if you need to show a dialog
        var b = (ChromiumWebBrowser)chromiumWebBrowser;

        if(!isProxy)
        {
            using (callback)
            {
                callback.Continue(username: "user", password: "pass");
            }

            return true;
        }

        //Return false to cancel the request
        return false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.