Asp MVC IIS User permission - asp.net

I use this code in my application to display some images stored on a network drive, for example with the path //MyCompanyServer/Folder
public ActionResult DocumentoLista(string area)
{
if (String.IsNullOrEmpty(area))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var doc = db.Documentos.Where(x => x.area == area).FirstOrDefault();
if (doc == null)
{
return HttpNotFound();
}
string dirPath = Path.GetFullPath(doc.path);
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
List<string> files = new List<string>();
DirectoryInfo dirInfo = new DirectoryInfo(dirPath);
foreach (string fInfo in Directory.EnumerateFiles(dirPath, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".png")
|| s.EndsWith(".PNG")
|| s.EndsWith(".jpg")
|| s.EndsWith(".JPG")
).Select(Path.GetFileName)
)
{
files.Add(fInfo);
}
ViewBag.Area = area;
ViewBag.Dirs = dirs;
ViewBag.MyList = files;
return View(doc);
}
It works perfectly on my dev machine but when I tried it from my deployment server, it doesn´t work. I think that maybe it´s not working because in my dev computer I´m executing it with my LDAP user and in my production server (IIS) the user is different and it doesn´t have permision to access to this path.
¿Could be?
Witch user executes asp applications? to what user do I need to give permissions in order to make it work?
Thanks

Pretty sure that the user your application pool is running under doesn't have permissions for that path, you need to:
Locate your application pool in IIS
Check the user account it's running against (In Basic Settings)
Give that user access to the path that you're trying to access (using windows security).

Give IUSR access to the folder.
http://www.iis.net/learn/get-started/planning-for-security/understanding-built-in-user-and-group-accounts-in-iis

Related

ASP.NET IIS File create permission while using Thread

I am trying to create a file in my ASP.NET application (IIS 7.5). The file write is done in a separate thread and is giving access not available error.
What kind of permission does the directory need? I have tried giving full access to IIS_IUSRS and IUSR. But this did not work. Everything works okay in my local machine, but once deployed on the server, I get access error.
string filePath = MapPath("c:\FilePath\");
PrintFile printFile = new PrintFile();
Thread printFileThread = new Thread(delegate()
{
printFile.PrintFile(filePath);
});
printFileThread.Start();
public void PrintFile(string filePath)
{
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
}
FileStream fs = new FileStream(filePath + "NewFile.pdf", FileMode.Create);
}

copy images from local machine to server in asp.net C#

I need to copy the images from C:/images folder to my web application folder which is running in the server.I used the following code which work well in local application but not work in server
string sourcePath = #"D:\images";
//string destinationPath = #"D:\a";
string destinationPath = Server.MapPath("SMSImages") + "\\";
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = Path.GetFileName(s);
destFile = Path.Combine(destinationPath, fileName);
File.Copy(s, destFile, true);
}
how to copy
Servers often have a lot of security limitations for the IIS user.
Check if the user under which you are running your asp.net process has authorization to access this path.
You can log the exceptions that are occurring in this code to see if it is causing an access violation.
The following code can help you check if code if you have access
UserFileAccessRights rights = new UserFileAccessRights(sourcePath);
if (rights.canWrite() && rights.canRead()) {
lblLogMsg.Text = "R/W access";
} else {
if (rights.canWrite()) {
lblLogMsg.Text = "Only Write access";
} else if (rights.canRead()) {
lblLogMsg.Text = "Only Read access";
} else {
lblLogMsg.Text = rights.ToString();
}
}
It doesn't work because the program search a D:\ path in server not in local system.

AppHarbor NopCommerce running issue

I uploaded nopcommerce solution to appharbor (using this method Can't build notcommerce project under appharbor) and solution succesfully builded, but I receiving 403 error - Forbidden: Access is denied when trying to open page(Allow write-access to file system is set to true).
Thanks and hope for your help
The problem is that the standard NopCommerce solution contains two Web Projects. AppHarbor only deploys one web project per application, and in this case, we happen to deploy Nop.Admin which is not what you want.
To resolve this, you should take advantage of the AppHarbor solution file convention and create an AppHarbor.sln solution file that only references the Nop.Web project.
We use a wrapper in our base controller to ensure that all of our code is oblivious to appharbor port changing.
First, fix in Webhelper.cs:75
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null)
return url;
if (includeQueryString)
{
string storeHost = GetStoreHost(useSsl);
if (storeHost.EndsWith("/"))
storeHost = storeHost.Substring(0, storeHost.Length - 1);
url = storeHost + _httpContext.Request.RawUrl;
}
else
{
#if DEBUG
var uri = _httpContext.Request.Url;
#else
//Since appharbor changes port number due to multiple servers, we need to ensure port = 80 as in AppHarborRequesWrapper.cs
var uri = new UriBuilder
{
Scheme = _httpContext.Request.Url.Scheme,
Host = _httpContext.Request.Url.Host,
Port = 80,
Path = _httpContext.Request.Url.AbsolutePath,
Fragment = _httpContext.Request.Url.Fragment,
Query = _httpContext.Request.Url.Query.Replace("?", "")
}.Uri;
#endif
url = uri.GetLeftPart(UriPartial.Path);
}
url = url.ToLowerInvariant();
return url;
}
So what we did is simply add files from https://gist.github.com/1158264 into Nop.Core\AppHarbor
and modified base controllers:
nopcommerce\Presentation\Nop.Web\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(RequestContext requestContext)
{
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current),
requestContext.RouteData));
}
//Same file from here downwards...
}
nopcommerce\Presentation\Nop.Web.Admin\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//set work context to admin mode
EngineContext.Current.Resolve<IWorkContext>().IsAdmin = true;
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current), requestContext.RouteData));
//base.Initialize(requestContext);
}
//Same file from here downwards...
}
Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
To do this, follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true
refrence :https://support.microsoft.com/en-us/kb/942062

Active Directory issues using IIS7 in Windows Server 2008 R2

The web app I'm working on uses both User ID's and Group ID's from Active Directory. That is, users can inherit access to some parts of the app (specifically reports) based on their membership in AD Groups.
So, we're using the User's GUID and Group's GUID as a key in the database tracking access to features.
App is working fine in development environment (IIS7 running on Windows 7). But when I try to set the site up in my test environment (IIS7 running on Windows Server 2008 R2), I get the following error:
Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.
From the stack trace, it appears that the guilty code is:
public string UserGUID
{
get
{
return UserPrincipal.Current.Guid.ToString();
}
}
I'm also accessing GroupPrincipals in a method that fetches all the groups a specific User belongs to:
public ArrayList Get_UserGroupGUIDs(string username)
{
ArrayList oList = new ArrayList();
// "company" is the domain we would like to search in
using ( PrincipalContext ctx = new PrincipalContext ( ContextType.Domain, "isidc.com" ) )
{
// get the user of that domain by his username, within the context
using ( UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username))
{
if (up != null)
{
// fetch the group list
using (PrincipalSearchResult<Principal> Groups = up.GetAuthorizationGroups())
{
foreach (GroupPrincipal g in Groups)
{
oList.Add(g.Guid.ToString());
} // end foreach
} // end using
} // end if
} // end using
return oList;
} // end method Get_UserGroupGUIDs
Any ideas?

How to list Windows users and groups in ASP.NET?

I have a ASP.NET Website project and I need to list all the users and their groups on my Windows system. I have set the identity impersonation to true and provided the username and password of the admin in the web.config. Where do I start?
Thanks in advance.
Update:
I have the following code at the moment -
var machine = new DirectoryEntry("WinNT://<IP ADDRESS>");
foreach (DirectoryEntry child in machine.Children)
{
// get the child's group(s).
}
When I debug, I can see the list of users in machine.Children. How do I find the group(s) that this user belongs to?
This article covers how to talk to Active Directory and should get you where you want to go:
http://www.codeproject.com/KB/system/everythingInAD.aspx
To get users, you would do something like this:
public List<string> GetUserList()
{
string DomainName="";
string ADUsername="";
string ADPassword="";
List<string> list=new List<string>();
DirectoryEntry entry=new DirectoryEntry(LDAPConnectionString, ADUsername, ADPassword);
DirectorySearcher dSearch=new DirectorySearcher(entry);
dSearch.Filter="(&(objectClass=user))";
foreach(SearchResult sResultSet in dSearch.FindAll())
{
string str=GetProperty(sResultSet, "userPrincipalName");
if(str!="")
list.Add(str);
}
return list;
}
You probably want to start with the DirectoryEntry and Active Directory support in .net.
Here's a good resource: http://www.codeproject.com/KB/system/everythingInAD.aspx
Local access is similar, even if you're not in a domain:
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" +
Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators",
"group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members) {
DirectoryEntry member = new DirectoryEntry(groupMember);
//...
}

Resources