Sunday, March 30, 2014

Upload/Access a File to network folder in asp.net

In my previous POST I had shown how to upload file in ASP.NET using the FileUpload control.

There might me lot of cases where your web server might no hold the 'n' number of files uploaded into the server. At this time your network guys may ask you to upload the file into a data server where you have lot of space. So, basically instead of storing it into the same server you will be forced to store it into a network folder.

Storing into a network folder is not a big deal. But when you are in a domain and your company have lot of security policies, then you might get into troubles uploading the file into the network folder.

First let me tell you how to show a network folder inside the FileUpload control.
Steps:-
1) Create a folder which is shared among Everyone to read/write let us say the path is \\smilu-pc\NetworkFolder\
2) Add the network path into the Fileupload's SaveAs method as shown below.


protected void UploadFileButton_Click(object sender, EventArgs e)
{
  FileUploadDocuments.SaveAs(@"\\smilu-pc\\NetworkFolder\\" + FileUploadDocuments.FileName);
}

If you have network access to this folder to write then you must be able to upload the files into it.

Now, If you don't have network access to these folders once you publish the website, you might get errors and the file may not be uploaded into the folder.


The above should not be the case always.
Your companies security policy will not allow you to share the folder for "Everyone" for writing/reading. So, It will be given to specific users. Here are some steps which will really help you to do these actions.

The most common error which you will find is written below

Exceptions:
System.UnauthorizedAccessException: Access to the path ' \\smilu-pc\NetworkFolder\filename.txt' is denied

When you try to upload the file the above exceptions might appear to you. And you will be struggling giving permissions to folder. When you run locally this will work very smoothly. But when you run this from webserver it will always throw the above error.

So, How can I solve this.
The best way to solve this is Identity Impersonation. You can look MSDN for its descriptions.
I'll give you a basic idea of it.
By default, Impersonation is disabled by asp.net and all the applications running in asp.net will not be having identity impersonation.
Identity Impersonation allows the Application to get authorized by a specific username and password when accessing the network folders or while doing some activities on the machines hence allowing it to work smoothly.

How to enable Identity Impersonation?

You can enable the Identity Impersonation in two ways.
1) Through web.config.
Adding the data into the Web.config is the best and the easiest way for working with Impersonation.

 <identity impersonate="true" userName="domain\smilu" password="password"/>

Writing this code into your system.web section of your web.config file will allow you to safely work with your application now. The user SMILU must be having access to the folder to write/read whatever is needed. The same user should also be part of the webserver's too(This I'm writing because I faced lot of issues when the user was not a part of my webserver)

If all the things are taken care of, which I have written above, you can run your application and you can see the Files getting saved into the network folder safely.

Hey see this, I can see your password now. Haha, now let me hack your machine.
Oops!! This is a major issue when you are working with Impersonation since the username and password is visible to others.
So, how can I solve this problem.
You can solve this in two ways

  • Encrypting identity section in web.config
  • Impersonation thorough code behind in asp.net
1) ENCRYPTING IDENTITY SECTION IN WEB.CONFIG
You are not joking right? Can we really encrypt the identity section in web.config??

Yes, Its not only identity section you can encrypt any section you need like Connection strings, app settings, identity section using asp.net and the asp.net will decrypt it for you.

How can you Encrypt a data in Web.config in asp.net?

Now, I will right the steps to encrypt the identity section in asp.net web.config file.
For this you must first open your command prompt and  navigate to your .net framework folder in your machine.

eg: C:\Windows\Microsoft.NET\Framework\v4.0.30319\


Now type the code below for encrypting the Identity section

aspnet_regiis -pef "system.web/identity" "D:\Smilu\Testing\WebserviceCalls"


To know what is aspnet_regiis tool go to the MSDN description of it.

Just a go through the code above

  • -pef - Will encrypt the section for you.
  • -pdf  - Will decrypt the section for you.
  • "system.web/identity" - The section which I need to encrypt
  • "D:\Smilu\Testing\WebserviceCalls" - The target web.config location in which i need to encrypt the data.

Let us see the web.config file before and after we run this command

Before Encrypting identity section in web.config

<identity impersonate="true" userName="domain\smilu" password="password"/>

Now after running the aspnet_regiis code on your command prompt

<identity configProtectionProvider="RsaProtectedConfigurationProvider">
 <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
 <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
 <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
 <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
  <KeyName>Rsa Key</KeyName>
 </KeyInfo>
 <CipherData>
  <CipherValue>uY1Wq5ZRRoWTuaR/4Xlst6/c1Rm9usaweg24XPd4OdMrJ4NDEkgM0vqECs4aCDy8F8JYX+lqzYRDHhj0V4QiHd16UPLqaGGfkPTm/3v6NRqM1Gv7r1fm2Rjagrc1V/zACL8OYHs/42VpDNpeyqDuf/70LLfTAaHjF9EX/tGJPBRRLqwfozHCv0Qjnm3i5Miuk0u19POzmX7+FZYQcnXNwN5EgvGeOKs+7FJNkidBHK1rVsdvjacpMSDICID2DQKlnuRPyXtjCJgqqFUawRolYEOuJGWgDZPAB/H0Ca/cRW3Dif3hCuD6qIc/LqqQo+xZOdXoJ/QPmO5oqURXge9SyQ==</CipherValue>
 </CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
 <CipherValue>zqM9DF/qBA04DKIZ/LfcNLjw8RVh6B+yimvxMF3p+UVW6KTaQS/2t0TvwfbRC5QjFFDWCZkM/4EZmmOtXlY773S+7z8DS4wFeTdeOQN1zctCmxypE8eNPQ==</CipherValue>
 </CipherData>
</EncryptedData>
</identity>
This is how it look when you encrypt the identity section. This section holds your username and password in an encrypted manner. If you can go through it you can find that here it has used RsaProtectedConfigurationProvider for encryption

So, This is how it is encrypted. Now, don't worry about how it works. Asp.net will decrypt it automatically when you are running the application.

Now, you are safe with your username and password as no one can read this.

Okay!! Now let me run the application.

Ohh god!  I met up with an error HTTP 500.19.

HTTP Error 500.19 - Configuration Section Encryption is Not Supported

Now, what you might be thinking? What is this guy talking about, He asked me to encrypt the section and now asp.net is saying encryption is not supported?

Don't worry when you see this error. You have a very simple fix for this.
Add this line of code to your web.config section. This time its not in the system.web section instead you must write the code in system.webserver section

<system.webServer>
   <validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Now, when you run the application it will run without that error.

Here, I have gone though the steps and possible issues you will face when you are trying to upload a file into a network folder. Hope this will help you a lot in uploading the files using asp.net fileupload control

In the next topic i will tell you how to programatically do impersonation.

Happy programming!

No comments: