ASP.NET Giving Access to directory by Username - asp.net

This can be done by making a new HTTP handler, but is there a simple way to configure the following?:
Site is setup on basis of user accounts with username say A001, A002....etc.
Once a user logs in they can access their resources in their directory (/A001) etc...which may contain files and images
The issue that I have had using roles and authorization in ASP.NET is that roles are either generic (defined by roles, example anyone logged in may be able to access the resource) or hard coded in the web.config files which is clearly not feasible in a dynamic environment where user accounts are being created:
<authorization>
<allow users="John"/> // allow John only
<deny users="*"/> // deny others
</authorization>
Is there a simple way to ensure that only a certain user has access to their folder only?

Well using an HTTP Module would be simple enough.
First this is the request life cycle:
Application_BeginRequest.
Application_AuthenticateRequest.
Application_PostAuthenticateRequest.
Application_DefaultAuthentication.
Application_AuthorizeRequest.
Application_PostAuthorizeRequest.
Application_ResolveRequestCache.
Application_PostResolveRequestCache.
Application_MapRequestHandler. Fired only when the server is running IIS 7 in Integrated Mode and at least >Net Framework 3.0
Application_PostMapRequestHandler.
Application_AcquireRequestState.
Application_PostAcquireRequestState.
Application_PreRequestHandlerExecute.
The page event handler is executed. (refer to the page life cycle)
Application_PostRequestHandlerExecute.
Application_ReleaseRequestState.
Application_PostReleaseRequestState
Application_UpdateRequestCache.
Application_PostUpdateRequestCache
Application_LogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
Application_PostLogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
Application_EndRequest.
For more info: http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx
I think the best event that fits your needs is the Application_AuthorizeRequest
Here you could get the path being accessed, and you could have a map in your database associating your uses with their allowed paths, something like:
UserID Path
userID1 ~/UserFiles/User1
userID2 ~/UserFiles/User2
userID3 ~/UserFiles/User3
Then in the event read this map and decide if the user should be authorized or not

Related

ASP.NET Remote File Access with Impersonation

I have an ASP.NET web application that is trying to read a remote share with the impersonated user. Specifically, I am trying to use the following code to read the directories on the remote share..
DirectoryInfo rootDir = new DirectoryInfo(strPath);
foreach (DirectoryInfo dir in rootDir.EnumerateDirectories())
{
TreeNode folderNode = new TreeNode(dir.Name, dir.FullName);
folderNode.PopulateOnDemand = true;
folderNode.ImageUrl = "~/img/Folder.png";
nodeList.Add(folderNode);
}
When the webpage runs this code, I get the following error message...
Access to the path '\remoteserver\remoteshare\' is denied.
Here is my web.config...
<authentication mode="Windows"/>
<identity impersonate="true" />
<authorization>
<deny users="?"/>
</authorization>
When I log onto the website, I know that impersonation is working because I can do an HttpContext.Current.User.Identity.Name and see my username. I am running this application on a domain under IIS 7.5. I also know that this can't be a Kerberos "double-hop" issue because I can connect to a remote SQL server (from the web server) and pass the Windows Authenticated credentials through just fine and return results from a query.
I am using Process Monitor on the web server to figure out which credentials are being passed over to the remote share. When I look at the capture where the ACCESS DENIED is showing, it gives me this description...
Desired Access: Read Data/List Directory, Synchronize, Disposition: Open, Options: Directory, Synchronous IO Non-Alert, Open For Backup, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a, Impersonating: DOMAIN\username
Where DOMAIN\username is my impersonated username from the web server.
Process Monitor is also showing that NT AUTHORITY\NETWORK SERVICE is the user on the web server that is making the request, which makes me think that the web server is NOT, in fact, passing over the impersonated user to read the remote file share. It's almost like there is a "double hop" issue for remote file share access specifically.
I have also configured the web server to "Trust this computer for delegation to any service (Kerberos only)". Again, this can't be a double-hop issue if I can access a remote SQL server from the web server, or can it? Any help or pointers would be greatly appreciated, I have spent 2 days looking at possible solutions and nothing works.

Passing Active Directory Credentials from an ASP.Net Page to Retrieve Web Content

I've got a site I recently converted from forms authentication to Windows authentication. I finally got it working correctly. I'm running into one issue that I haven't found a suitable workaround for yet. We have several pages that from within the backend code will call other pages and retrieve content sections from the returned page. Since the code is calling the other page, I am getting an access denied error (the code can't pass the authentication). I've tried several ways of passing windows credentials with the request and all have failed.
I'm willing to create an AD user for this function and hardcode the username and password with the request so that the information can be retrieved. Can anyone give me code that will allow me to do this, so far I've been unsuccessful. Thanks.
-Edit-
I don't remember them all, but here's the last one I tried:
Dim wc As New WebClient()
Dim credential As NetworkCredential = New NetworkCredential(ADusername, ADPwd, ADDomain)
wc.Credentials = credential
Dim strXML As String = wc.DownloadString(RssFeedUrl)
This causes the page to return (401) Unauthorized.
Another thing I tried... one of the 'retrievals' is an RSS feed, this is the location of the feed.
<location path="RSS.ashx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
It didn't seem to help.
Turns out that after some more testing, I found that the code above actually works. I copied it to a windows application and ran it on several machines. All worked correctly with the exception of the server I wanted to host the code on. Did some digging into the Event viewer and there were some failed security audits. Using this information I found that there is a 'loopback check' on the server. Using Microsoft KB article 896861 I disabled the loopback check for the site and voila! it is now working.

ASP.NET Authentication cookies (Web Farm)

I use FormsAuthentication
I have a web farm with 2 nodes. What I do :
1) I log-in to my site by means of my factory through 1st node and go to default page.
2) I switch off 1st node, so next request should be to my 2nd node.
3) I'm trying to request some page(which should be available if I'm logged in) but application redirects me to login url. I think because of incorrect or missing cookies.
I used machine key
something like :
<machineKey
validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F"
validation="SHA1" />
But It still do not work.
I am doing almost the same as described here :
http://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx
But it just do not work for me.
What am I doing wrong ?
The problem was in security updates.
As soon as we installed updates the problem was solved.
Here is the list of possible updates which impact on this:
Security Update KB2656351
Security Update KB2487376
Security Update KB2633870
Security Update KB2572078
Security Update KB2518870

ASP.NET Session TimeOut problem

I have a wired scenario in one of my ASP.net application.
I am using ASP.net membership with my custom "roleManager",
and having below tag in web.config to restrict any user not having role of "Keywords"(roles) to access "Keywords"(path) folder
<location path="Keywords">
<system.web>
<authorization>
<allow roles="Keywords"/>
<deny users="*" />
</authorization>
</system.web>
</location>
If any user with some other role allow to assess this URL (Keywords in this case) will be redirected to a custom- Access denied page.
Now things working fine but when I left my application with a inactivity of 30 min I am not able to visit the "Keywords", all the time I end up with the custom- Access denied page, if I close the browser, login again it start working fine.
Please help me in this case.
Thanks in advance
ASP.NET sessions time out after 20 minutes by default, I think.
You can extend this by specifying a longer time (in minutes) in the Web.config:
<system.web>
<sessionState timeout="60"/>
...
</system.web>
If you are authenticating via Forms, you should raise the authentication cookie timeout value to match.
Also bear in mind that, when running the site under IIS, you should probably extend the application pool's idle timout to something similar. If you don't do this, the HttpApplication instance for your ASP.NET site will be unloaded, destroying any active sessions in the process.
Usually, the first and easiest thing to do is just change the configuration/system.web/sessionState#timeout value to something like “90″
<sessionState timeout="90" />
it still appears to be timing out after 20 minutes.
*This doesn’t make any sense, it explicitly says that the session timeout should be exactly 90 minutes.*
There’s a couple of issues that are tied together here:
The application pool’s worker process default idle timeout is also
set to 20 minutes
The default mode of storing session state is in the IIS process
The settings for the application pool can be found by clicking Properties (IIS 6) or Advanced Settings (IIS 7.5) on the application pool that the application is assigned to.
Ensure the value of "Idle-Time-out(minutes)" is set to the timeout of your session, at a minimum (ex 90), to ensure that all sessions persist for the entire session timeout period.
try this solution if still there is a problem refer to this article it tell more option to try
http://asp-net.vexedlogic.com/2012/05/23/aspasp-net-session-timeout-how-do-i-change-it/

Strange logging off on ASP.NET 3.5 website

Please help me I'm getting desperate here trying to find the problem, and I don't know where to start looking for it.
Here are the symptoms:
I've noticed, that when a user logs on in the morning, he is then immediately logged off, then when he logs on again, everything is fine and he can work on the site.
Every once in a while, when the user clicks a link, the page takes a lot of time to load, but it never actually loads, and the user is thrown to the login page.
Also, after an Exception has occurred in the website, the user is then thrown to the login page. It's as if the exception clears somehow the session.
Do any of you know of a situation where this might happen ?
The code I use in every page in my application is as follows :
If (Not User.Identity.IsAuthenticated) Then
Response.Redirect("../login2.aspx")
End If
' If session timeout then return to login screen '
If ((Session("LocationId") Is DBNull.Value) Or (Session("LocationId") Is Nothing))
Then
Response.Redirect("../login2.aspx")
End If
The code in the web.config:
<sessionState cookieless="false" timeout="600" />
<authentication mode="Forms">
<forms timeout="600" />
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
Why are you using that code in every page?
.NET authorization and authentication normally takes care of all those things if you have it set up correctly.
Related to this scenario *`
".... after an Exception has occurred
in the website, the user is then
thrown to the login page. It's as if
the exception clears somehow the
session
I know of one possible situation where it may occur.
It is far fetched especially in a production scenaio for multiple reasons but i have seen it happen :-)
If the session is In Memory and logging is done by writing to a log file that is in the Bin directory of the application, then this may occur as modifying the bin folder of the web application results in the application restarting i.e the in memory session getting lost.
Just one possible scenario. If your session is not in Memory OR your logging mechanism isnt like this, then this doesnt apply to you.
I am turning to all the dot net experts out there because I am really desperate,
let me give another symptom of the problem because it still persists,
the server is a very strong server - intel xeon with a 3 gb ram, so it is probably not a problem of resources.
When the user uses the system continuously there is no problem and she can work freely, the problem arises when the user leaves the computer (or the application for that matter) for as long as 5 minutes, then when she wants to continue working and clicks a link in the application she is thrown to the login page. when she tries to login again, she succeeds, but after she clicks another link, she is thrown out again, then when she logins she can work freely and everything is fine.
Somehow the session is being cleared when the site is idle. let me emphasize that this doesn't happen when I run the app in visual studio, only in iis.
The app was converted from asp.net 2.0 to 3.5,
that's it, thanks
First of all, you need to deny access for non-authenticated (anonymous) users:
<authorization>
<deny users="?" />
</authorization>
Have you configured default and login pages?
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" loginUrl="Login.aspx" defaultUrl="Default.aspx" slidingExpiration="true" timeout="30" />
</authentication>
name sets the name of a cookie, useful if you will use .NET 2.0 built-in security infrastructure (roles, membership, etc)
slidingExpiration enabled normal timeout behavior - any user action resets timeout
If you are just using the normal session functionality in asp.net I believe that the session times out after 15-30 minutes of inactivity (I typically don't use session so I remember it is somewhere in this range). Every postback to the server resets this timer so if a user is active doing things then they won't hit this time out.
For the page taking a long time to load it is most likely due to the worker process recycling and that user is the first user to access the site after a recycle which triggers IIS to do all of it's compilation stuff and then serve the page which causes the delay. This only happens for the first visitor after a worker process recycle. You can change this behavior in IIS to happen on a schedule rather than after a certain amount of time has passed without activity. This will cause your worker process to take up more memory though so depending on your environment this might not be a good change to make.
EDIT: I should add that the code you posted explains exactly why the user is kicked back to the login page. It is checking to make sure that there is something in the session and if there isn't anything there it kicks the user back to the login page. So if they are inactive for too long your session times out, so it is cleared, and the user is kicked back to the login page by your code. Also you should use FormsAuthentication.RedirectToLoginPage(); for your redirect instead of Response.Redirect. This way after logging in they go back to the page they requested originally.

Resources