Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Use Windows credentials to download file in Windows form app

Posted on 2008-06-11
3
Medium Priority
?
1,109 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 11

Accepted Solution

by:
AkisC earned 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

598 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