Saturday, January 29, 2011

Automate windows authentication process in browser

Once i was faced issue to show the windows authenticated site  browser control in window application.

Becuase it shows pop-up to ask credentials but i want to automate that task so that it not ask for

credential when passed in code.

For that form class has to be implemented from

IOleClientSite, IServiceProvider, IAuthenticate
 
definitions for that you can find on net.
 
after insert defination of above inside our project inside on class you can implement that 
inside form code.
 
So then on form load you have to first move to "about.blank" page before actually navigate
the page you want to access. Because it useful to eliminate issue IE sometimes not
call authenicate process of IAuthentiate at first run.
So form load event has to be something like
private void form1_Load(object sender, EventArgs e)
    {
 
//Navigate to about:blank to avoid authentication
// issue on Ie
    string oURL = "about:blank";
    webBrowser1.Navigate(oURL);

   // NOe set the ole object 
    object obj = webBrowser1.ActiveXInstance;
    IOleObject oc = obj as IOleObject;
    oc.SetClientSite(this as IOleClientSite);
    } 

 two methods which needs to be implemented here is as below
 
public static Guid IID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
    public const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
    public const int S_OK = unchecked((int)0x00000000);
 
 
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
    {
    int nRet = guidService.CompareTo(IID_IAuthenticate); // Zero returned if the compared objects are equal
    if (nRet == 0)
    {
    nRet = riid.CompareTo(IID_IAuthenticate); // Zero returned if the compared objects are equal
    if (nRet == 0)
    {
    //This method returns an interface pointer that represents the requested interface on the specified object. It is particularly useful if you have an unmanaged method that expects to be passed an interface pointer; Add to the COM interface reference count.
    ppvObject = Marshal.GetComInterfaceForObject(this, typeof(IAuthenticate));
    return S_OK;
    }
    }
    ppvObject = new IntPtr();
    return INET_E_DEFAULT_ACTION;
    }
 
 public int Authenticate(ref IntPtr phwnd, ref IntPtr pszUsername,
    ref IntPtr pszPassword)
    {
    //Copies the contents of a managed String to a block of memory allocated from the unmanaged COM task allocator.
    IntPtr strUser = Marshal.StringToCoTaskMemAuto(txtUserID.Text);
    IntPtr strPassword = Marshal.StringToCoTaskMemAuto(txtPassword.Text);


    pszUsername = strUser;
    pszPassword = strPassword;
    return S_OK;
    }
 
 
 
I hope this above information is useful to resolve the issue  like i have faced.
 
If you want the complete souce code implementation than mail me. i will be back to you with that.
 
 
 
Thanks
Tushar 
 
 
 

No comments:

Post a Comment