Use Windows credentials to download file in Windows form app

Posted on 2008-06-11
Last Modified: 2013-11-07
I'm writing a Windows form application (.NET 2.0, VS2008).  I need the app to download some files from an intranet site, but only allow users who are members of a specific AD group to download these files.  I've setup the AD group and IIS permissions with no problems.  Now I'm a little stuck how to get the right user credentials to download the file with.

As far as I understand, if the user is logged into the AD and I set webclient.UseDefaultCredentials to true, it will pass through the user credentials OK.  The scenario I need to allow for is a user who is logged onto their PC locally.  I'll need it to prompt for their domain credentials and then pass it to webclient.credentials.  This is where I need a hand.  Any ideas on how I should cater for that scenario?  I've been looking into ICredentials and related bit 'n' pieces and it's got me a littlle baffled.

Any information, suggestions or samples would be appreciated.  Thanks.
Question by:sj_hicks
LVL 11

Accepted Solution

AkisC earned 500 total points
Comment Utility

        Dim myDomainName As String = "", thisUserName As String = "", thisPassword As String = ""
        '//////Make a form and ask your user to provide their credentials [myDomainName , thisUserName, thisPassword]

        Dim imp As New RunAs_Impersonator
            imp.ImpersonateStart(myDomainName, thisUserName, thisPassword) 'creates new context using token for user
            '//Add code to run as UserName here
            'everything between ImpersonateStart and ImpersonateStop will be run as the impersonated user
        Catch ex As Exception 'make sure impersonation is stopped whether code succeeds or not
        End Try
Imports System

Imports System.Runtime.InteropServices

Imports System.Security.Principal

Imports System.Security.Permissions

Imports Microsoft.VisualBasic

<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True), _

 Assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name:="FullTrust")> 

Public Class RunAs_Impersonator

#Region "Private Variables and Enum Constants"

    Private tokenHandle As New IntPtr(0)

    Private dupeTokenHandle As New IntPtr(0)

    Private impersonatedUser As WindowsImpersonationContext

#End Region

#Region "Properties"

#End Region

#Region "Public Methods"

    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

    Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _


      ByRef DuplicateTokenHandle As IntPtr) As Boolean

    ' Test harness.

    ' If you incorporate this code into a DLL, be sure to demand FullTrust.

    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _

    Public Sub ImpersonateStart(ByVal Domain As String, ByVal userName As String, ByVal Password As String)


            tokenHandle = IntPtr.Zero

            ' Call LogonUser to obtain a handle to an access token.

            Dim returnValue As Boolean = LogonUser(userName, Domain, Password, 2, 0, tokenHandle)

            'check if logon successful

            If returnValue = False Then

                Dim ret As Integer = Marshal.GetLastWin32Error()

                Console.WriteLine("LogonUser failed with error code : {0}", ret)

                Throw New System.ComponentModel.Win32Exception(ret)

                Exit Sub

            End If

            'Logon succeeded

            ' Use the token handle returned by LogonUser.

            Dim newId As New WindowsIdentity(tokenHandle)

            impersonatedUser = newId.Impersonate()

        Catch ex As Exception

            Throw ex

            Exit Sub

        End Try

        MsgBox("running as " & impersonatedUser.ToString & " -- " & WindowsIdentity.GetCurrent.Name)

    End Sub

    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _

    Public Sub ImpersonateStop()

        ' Stop impersonating the user.


        ' Free the tokens.

        If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then


        End If

        MsgBox("running as " & Environment.UserName)

    End Sub

#End Region

#Region "Private Methods"

    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _

     ByVal lpszDomain As [String], ByVal lpszPassword As [String], _

     ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _

     ByRef phToken As IntPtr) As Boolean

    <DllImport("kernel32.dll")> _

    Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _

     ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _

     ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer

    End Function

#End Region

End Class

Open in new window


Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now