Connecting to a UNC share from a web application

Discussion in 'ASP .Net Security' started by Rasmus, Jan 6, 2005.

  1. Rasmus

    Rasmus Guest

    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
     
    Rasmus, Jan 6, 2005
    #1
    1. Advertising

  2. Rasmus

    Paul Clement Guest

    On Thu, 6 Jan 2005 07:59:06 -0800, Rasmus <> wrote:

    ¤ 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 ~~~
    Microsoft MVP (Visual Basic)
     
    Paul Clement, Jan 6, 2005
    #2
    1. Advertising

  3. Rasmus

    Rasmus Guest

    Rasmus, Jan 6, 2005
    #3
  4. Rasmus

    Rasmus Guest

    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
     
    Rasmus, Jan 7, 2005
    #4
  5. Rasmus

    [MSFT] Guest

    Hello,

    I think you may try impersonate in ASP.NET. This can make your ASP.NET app
    act as a designed user and use this user's permission to access network
    share. This can be implement with either asp.net config file or code. For
    details, you may refer to:

    How to implement impersonation in an ASP.NET application
    http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q306158

    Luke
     
    [MSFT], Jan 7, 2005
    #5
  6. Rasmus

    Rasmus Guest

    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
    }
    }
     
    Rasmus, Jan 7, 2005
    #6
  7. Rasmus

    Paul Clement Guest

    On Thu, 6 Jan 2005 12:53:01 -0800, Rasmus <> wrote:

    ¤ 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 ~~~
    Microsoft MVP (Visual Basic)
     
    Paul Clement, Jan 7, 2005
    #7
  8. Rasmus

    Rasmus Guest

    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?
     
    Rasmus, Jan 7, 2005
    #8
  9. Rasmus

    Paul Clement Guest

    On Fri, 7 Jan 2005 08:07:05 -0800, Rasmus <> wrote:

    ¤ 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 ~~~
    Microsoft MVP (Visual Basic)
     
    Paul Clement, Jan 7, 2005
    #9
  10. Rasmus

    [MSFT] Guest

    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
     
    [MSFT], Jan 10, 2005
    #10
  11. Rasmus

    Rasmus Guest

    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>
     
    Rasmus, Jan 18, 2005
    #11
  12. Rasmus

    vetplakh Guest

    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" wrote:

    > 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>
    >
     
    vetplakh, Jan 18, 2005
    #12
  13. Rasmus

    Rasmus Guest

    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.
     
    Rasmus, Jan 18, 2005
    #13
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Simon Chung-Jen Chuang
    Replies:
    1
    Views:
    4,016
    Ken Schaefer
    Aug 23, 2003
  2. Gaetano D'Aquila

    Connect to a netword share via UNC name

    Gaetano D'Aquila, Jan 19, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    620
    Gaetano D'Aquila
    Jan 19, 2004
  3. =?Utf-8?B?cGpfc2VydmFkbWlu?=

    Running an asp.net application on a remote share (UNC) - parser er

    =?Utf-8?B?cGpfc2VydmFkbWlu?=, Jun 20, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    2,605
    =?Utf-8?B?cGpfc2VydmFkbWlu?=
    Jul 1, 2005
  4. BrianS

    Asp.Net Web Service accessing file on UNC share

    BrianS, Feb 10, 2005, in forum: ASP .Net Security
    Replies:
    2
    Views:
    211
    Joe Kaplan \(MVP - ADSI\)
    Feb 11, 2005
  5. Saraswati lakki
    Replies:
    0
    Views:
    1,390
    Saraswati lakki
    Jan 6, 2012
Loading...

Share This Page