Connecting to a UNC share from a web application

R

Rasmus

Basically I want to do the following:

DirectoryInfo baseDirInfo = new DirectoryInfo(@"\\server2\files");
FileInfo[] aFileInfos = baseDirInfo.GetFiles();
string ss = "";
foreach (FileInfo fileInfo in aFileInfos){
ss += fileInfo.Name;
}


But I need a way to supply the username and password – otherwise I’m not
allowed to access the share.

Info:
The web application has anonymous access
No domain
A local user is created on server2
This user has access to share d:\files on server2
 
P

Paul Clement

¤ Basically I want to do the following:
¤
¤ DirectoryInfo baseDirInfo = new DirectoryInfo(@"\\server2\files");
¤ FileInfo[] aFileInfos = baseDirInfo.GetFiles();
¤ string ss = "";
¤ foreach (FileInfo fileInfo in aFileInfos){
¤ ss += fileInfo.Name;
¤ }
¤
¤
¤ But I need a way to supply the username and password – otherwise I’m not
¤ allowed to access the share.
¤
¤ Info:
¤ The web application has anonymous access
¤ No domain
¤ A local user is created on server2
¤ This user has access to share d:\files on server2

Take a look at the below link concerning delegation scenarios:

http://msdn.microsoft.com/library/d...y/en-us/vsent7/html/vxconaspnetdelegation.asp


Paul ~~~ (e-mail address removed)
Microsoft MVP (Visual Basic)
 
R

Rasmus

Server name: server2
unc: \\server2\junk
username: test
password: pass

More info on what i can do and not:

In cmd window:
net use x: \\server2\junk /user:server2\test pass

this will map the unc to drive x - and everything works fine.

But using the same username password in the code snippet from
http://msdn.microsoft.com/library/d...cipalWindowsIdentityClassImpersonateTopic.asp

I get:
Enter the name of the domain on which to log on: \\server2\junk
Enter the login of a user on \\apollo6\ros that you wish to impersonate:
server2\test
Enter the password for server2\test: pass
LogonUser called.
LogonUser failed with error code : 1326

Error: [1326] Logon failure: unknown user name or bad password.


Exception occurred. Access is denied




please help
 
R

Rasmus

Hello,

Thanks for the reply. But i still cant get it to work. with the following
code:



using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace nws
{
/// <summary>
/// Summary description for WebForm2.
/// </summary>
public class WebForm2 : System.Web.UI.Page
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

public void Page_Load(Object s, EventArgs e) {
if(impersonateValidUser("test", "server2", "pass")) {
Response.Write("HURRA");
//Insert your code that runs under the security context of a specific
user here.
undoImpersonation();
}
else {
Response.Write("BUMMER");
//Your impersonation failed. Therefore, include a fail-safe mechanism
here.
}
}

private bool impersonateValidUser(String userName, String domain, String
password) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if(RevertToSelf()) {
if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0) {
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null) {
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if(token!= IntPtr.Zero)
CloseHandle(token);
if(tokenDuplicate!=IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

private void undoImpersonation() {
impersonationContext.Undo();
}


#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
 
P

Paul Clement

¤ Thank you for the reply.
¤
¤ I've tried the approach from
¤ http://msdn.microsoft.com/library/d...cipalWindowsIdentityClassImpersonateTopic.asp
¤
¤ But keep getting "Error: [1326] Logon failure: unknown user name or bad
¤ password."
¤
¤ I'm trying to connect to a XP with a shared folder

Assuming here that you're using a local account and that it exists on both machines and has the same
password?


Paul ~~~ (e-mail address removed)
Microsoft MVP (Visual Basic)
 
R

Rasmus

Hi Paul,

No i did not have the test user on both machines. I tried it and it still
did not work.
I noticed this in the code comment:
"This sample can be run only on Windows XP. "

The client in my case is a windows server 2003 - could that be the cause?
 
P

Paul Clement

¤ Hi Paul,
¤
¤ No i did not have the test user on both machines. I tried it and it still
¤ did not work.
¤ I noticed this in the code comment:
¤ "This sample can be run only on Windows XP. "
¤
¤ The client in my case is a windows server 2003 - could that be the cause?

Have you tried changing the Anonymous account under which the web application is running (it's
probably IUSR_machinename, which can't be delegated) and then just using the standard impersonation
(web.config setting for your ASP.NET app)? If this works then it would eliminate the need for the
impersonation code you've written.

In any event, for delegation to function properly, the local account must exist on both machines and
have the same password.

I'm not sure what impact Windows Server 2003 would have in this configuration. It's a more secure OS
that was designed to operate in a domain based environment.


Paul ~~~ (e-mail address removed)
Microsoft MVP (Visual Basic)
 
M

[MSFT]

It seems there is no problem with the code. As Paul suggested, have you
checked the anonymous access in the IIS security setting? Also, how did you
set the authentication in web.config?

Luke
 
R

Rasmus

Anonymous is checked and user is IUSR_<Machine name>

Web config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<system.web>

<!-- DYNAMIC DEBUG COMPILATION
Set compilation debug="true" to enable ASPX debugging. Otherwise,
setting this value to
false will improve runtime performance of this application.
Set compilation debug="true" to insert debugging symbols (.pdb
information)
into the compiled page. Because this creates a larger file that
executes
more slowly, you should set this value to true only when debugging
and to
false at all other times. For more information, refer to the
documentation about
debugging ASP.NET files.
-->
<compilation
defaultLanguage="c#"
debug="true"
/>

<!-- CUSTOM ERROR MESSAGES
Set customErrors mode="On" or "RemoteOnly" to enable custom error
messages, "Off" to disable.
Add <error> tags for each of the errors you want to handle.

"On" Always display custom (friendly) messages.
"Off" Always display detailed ASP.NET error information.
"RemoteOnly" Display custom (friendly) messages only to users not
running
on the local Web server. This setting is recommended for security
purposes, so
that you do not display application detail information to remote
clients.
-->
<customErrors
mode="RemoteOnly"
/>

<!-- AUTHENTICATION
This section sets the authentication policies of the application.
Possible modes are "Windows",
"Forms", "Passport" and "None"

"None" No authentication is performed.
"Windows" IIS performs authentication (Basic, Digest, or
Integrated Windows) according to
its settings for the application. Anonymous access must be
disabled in IIS.
"Forms" You provide a custom form (Web page) for users to enter
their credentials, and then
you authenticate them in your application. A user credential
token is stored in a cookie.
"Passport" Authentication is performed via a centralized
authentication service provided
by Microsoft that offers a single logon and core profile services
for member sites.
-->
<authentication mode="None" />

<!-- AUTHORIZATION
This section sets the authorization policies of the application.
You can allow or deny access
to application resources by user or role. Wildcards: "*" mean
everyone, "?" means anonymous
(unauthenticated) users.
-->

<authorization>
<allow users="*" /> <!-- Allow all users -->
<!-- <allow users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
<deny users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
-->
</authorization>

<!-- APPLICATION-LEVEL TRACE LOGGING
Application-level tracing enables trace log output for every page
within an application.
Set trace enabled="true" to enable application trace logging. If
pageOutput="true", the
trace information will be displayed at the bottom of each page.
Otherwise, you can view the
application trace log by browsing the "trace.axd" page from your
web application
root.
-->
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>

<!-- SESSION STATE SETTINGS
By default ASP.NET uses cookies to identify which requests belong
to a particular session.
If cookies are not available, a session can be tracked by adding a
session identifier to the URL.
To disable cookies, set sessionState cookieless="true".
-->
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>

<!-- GLOBALIZATION
This section sets the globalization settings of the application.
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>

</system.web>

</configuration>
 
V

vetplakh

I guess the root of your problems is in the following quote from the Platform
SDK:
"The LogonUser function attempts to log a user on to the local computer. The
local computer is the computer from which LogonUser was called. You cannot
use LogonUser to log on to a remote computer."

So my suggestions are:

1. Try use "." instead of domain name when calling LogonUser - that might
solve the problem of ivalid user or password.

2. LogonUser can't be used at all (as I understood from other discussions)
to solve the problem of accessing shared resources on other computers. To
solve that problem you have to configure delegation on all computers
involved.

3. Or am I mistaken?..

Rasmus said:
Anonymous is checked and user is IUSR_<Machine name>

Web config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<system.web>

<!-- DYNAMIC DEBUG COMPILATION
Set compilation debug="true" to enable ASPX debugging. Otherwise,
setting this value to
false will improve runtime performance of this application.
Set compilation debug="true" to insert debugging symbols (.pdb
information)
into the compiled page. Because this creates a larger file that
executes
more slowly, you should set this value to true only when debugging
and to
false at all other times. For more information, refer to the
documentation about
debugging ASP.NET files.
-->
<compilation
defaultLanguage="c#"
debug="true"
/>

<!-- CUSTOM ERROR MESSAGES
Set customErrors mode="On" or "RemoteOnly" to enable custom error
messages, "Off" to disable.
Add <error> tags for each of the errors you want to handle.

"On" Always display custom (friendly) messages.
"Off" Always display detailed ASP.NET error information.
"RemoteOnly" Display custom (friendly) messages only to users not
running
on the local Web server. This setting is recommended for security
purposes, so
that you do not display application detail information to remote
clients.
-->
<customErrors
mode="RemoteOnly"
/>

<!-- AUTHENTICATION
This section sets the authentication policies of the application.
Possible modes are "Windows",
"Forms", "Passport" and "None"

"None" No authentication is performed.
"Windows" IIS performs authentication (Basic, Digest, or
Integrated Windows) according to
its settings for the application. Anonymous access must be
disabled in IIS.
"Forms" You provide a custom form (Web page) for users to enter
their credentials, and then
you authenticate them in your application. A user credential
token is stored in a cookie.
"Passport" Authentication is performed via a centralized
authentication service provided
by Microsoft that offers a single logon and core profile services
for member sites.
-->
<authentication mode="None" />

<!-- AUTHORIZATION
This section sets the authorization policies of the application.
You can allow or deny access
to application resources by user or role. Wildcards: "*" mean
everyone, "?" means anonymous
(unauthenticated) users.
-->

<authorization>
<allow users="*" /> <!-- Allow all users -->
<!-- <allow users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
<deny users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
-->
</authorization>

<!-- APPLICATION-LEVEL TRACE LOGGING
Application-level tracing enables trace log output for every page
within an application.
Set trace enabled="true" to enable application trace logging. If
pageOutput="true", the
trace information will be displayed at the bottom of each page.
Otherwise, you can view the
application trace log by browsing the "trace.axd" page from your
web application
root.
-->
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>

<!-- SESSION STATE SETTINGS
By default ASP.NET uses cookies to identify which requests belong
to a particular session.
If cookies are not available, a session can be tracked by adding a
session identifier to the URL.
To disable cookies, set sessionState cookieless="true".
-->
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>

<!-- GLOBALIZATION
This section sets the globalization settings of the application.
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>

</system.web>

</configuration>
 
R

Rasmus

Thank you for the suggestions.

I just can’t seem to understand why, when I have all the necessary login
information (UNC, username and password), I cannot retrieve the files and
folders on the UNC share.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top