开发者

How to set proxy authentication on Internet explorer?

I've been trying to set the user and password for the IE proxies for a while without having good results, I try with WebProxy, WebClient and now i'm trying with InternetSetOption from Wininnet.dll, the idea behind this is to avoid the input of the user and password each time a user open a browser. Here is the code:

using System;
using System.Collections开发者_StackOverflow社区.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Net;
using System.ComponentModel;

namespace Proxy.Core
{
    public class ProxyImpersonator
    {
        private const int INTERNET_OPTION_PROXY_USERNAME = 43;
        private const int INTERNET_OPTION_PROXY_PASSWORD = 44;

        private const int INTERNET_OPEN_TYPE_PRECONFIG = 0; // use registry configuration
        private const int INTERNET_OPEN_TYPE_DIRECT = 1; // direct to net
        private const int INTERNET_OPEN_TYPE_PROXY = 3; // via named proxy
        private const int INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY = 4; // prevent using java/script/INS

        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool InternetSetOption(IntPtr hInternet, int
        dwOption, string lpBuffer, int dwBufferLength);

        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern IntPtr InternetConnect(
           IntPtr hInternet, string lpszServerName, short nServerPort,
           string lpszUsername, string lpszPassword, int dwService,
           int dwFlags, IntPtr dwContext);

        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern IntPtr InternetOpen(
           string lpszAgent, int dwAccessType, string lpszProxyName,
           string lpszProxyBypass, int dwFlags);

        public static void Impersonate(Proxy Config)
        {
            IntPtr hOpen = InternetOpen("Proxy Connection", INTERNET_OPEN_TYPE_PROXY,Config.Address.ToString(),String.Empty, 0);
            IntPtr hInternet = InternetConnect(hOpen, Config.Address.URL, short.Parse(Config.Address.Port.ToString()), Config.UserID, Config.UserPwd, 3, 0, IntPtr.Zero);

            if (!InternetSetOption(hInternet,INTERNET_OPTION_PROXY_USERNAME,Config.UserID,Config.UserID.Length+1))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!InternetSetOption(hInternet, INTERNET_OPTION_PROXY_PASSWORD, Config.UserPwd, Config.UserPwd.Length + 1))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }

    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜