Solved

Use Windows credentials to download file in Windows form app

Posted on 2008-06-11
3
1,095 Views
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.
0
Comment
Question by:sj_hicks
3 Comments
 
LVL 11

Accepted Solution

by:
AkisC earned 500 total points
ID: 21775874

        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
        Try
            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
            imp.ImpersonateStop()
        Catch ex As Exception 'make sure impersonation is stopped whether code succeeds or not
            imp.ImpersonateStop()
            MsgBox(ex.Message)
        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, _

      ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _

      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)

        Try

            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.

        impersonatedUser.Undo()
 

        ' Free the tokens.

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

            CloseHandle(tokenHandle)

        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

0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to save a picture box in a specific network folder using vb.net 2013 7 26
C# Offline Apllication 5 54
Close tabpage of custom control 9 23
Help with Syntax 9 26
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
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 Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …

912 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

20 Experts available now in Live!

Get 1:1 Help Now