c# asp.net getting username - c#

"Have you ever done any .net programming? Yes? Good, here's a massive broken program, fix it". That is the situation I'm in, so sorry if it's an easy question.
The program I am working on pulls a file from a web server. It is expected that the user is already logged into the web server. I need to pull the username of the current person logged into the server (or just make sure someone is indeed logged into the server).
I have tried the following and it returns an empty string.
user = HttpContext.Current.User.Identity.Name;

Please make sure you are setting windows authentication in Web.Config file. Also check the following before accessing the username,
HttpContext.Current.User.Identity.IsAuthenticated
Set Web.Config as follows,
<authentication mode="Windows"></authentication>

First check in Web.config file for <authentication> tag.
If you don't find it then your application may not be using any standard authentication mechanism. If that is the case look inside the login.aspx or whatever code that does the authentication. There you will get hold of logged in user data.
I wouldn't recommend you to change anything in web.config file without having some firm grasp on whats going in the application.

The properties of the User object are usually populated by the application's authentication scheme (Forms, Windows or Custom) so you'll need to ensure one of these is in place before commencing to access the User.
For more information, take a look at the docs at MSDN.

Related

Multiple anonymous users can't access .NET web app simultaneously

I have a .NET a web app that i built for files processing .I am using IIS 7 anonymous user authentication , i also did not require the users to log in, so pretty much any user who has access to the intranet can access the web app.
The users said when two of them try to run their files on app at the same time they receive an error( did not specify it).
My question is :
If i use anonymous authentication is it by default every user will have his\her own session while accessing the app?
Yes, by default every user will have their own session. And anonymous authentication is the default scheme for the web. It is unlikely that any web server, by default, would only allow 1 anonymous user at a time.
Most likely, if your app is doing file processing, you may be dealing with file locks and not an issue with IIS. You want to make sure that your code is written so that, if two or more people access it simultaneously, they can not request to same file. Also, you need to make sure that you are properly closing any file streams you open, even in the case of exceptions. Without seeing the code in question, it would be difficult to impossible to give more specific guidance, but hopefully this will help point you in the correct direction.
Install Elmah to get error report of ypur app!

asp.net c# web app with active directory and windows authentication

i'm currently developing an intranet web app, with a homepage and several departmental pages, the web app is merely for viewing information so everyone will have the same privileges. i've reached a point that i must worry about the app's access and authentication, my company has an active directory with several groups that i can use, after searching for a while i got the following questions:
in the webconfig file, i forced windows authentication and blocked users that are not authenticated (deny users = ?)
i saw somewhere that i need several webconfig files, one for each page, is that so? how do it make each page connect to the corresponding webconfig?
after looking at some examples i can't figure out my AD connection string (i'm currently on a development machine), our AD groups are on our domain controller, the physical location is "DCserver.company_name.local\city folder\groups"
do i need to create a login page? i mean doesn't that kinda go against the point of having windows authentication?
i don't need to manage anything within the AD, i simply want to read the groups and ensure that, for example, the marketing people only have access to the homepage and the marketing departmental page
as i've mentioned up there, there will be no special special privileges, the user from, for example, marketing will be able to click everything within his departmental page
i'm sorry for all the questions, but i'm relatively new to c# and .net development
Following are the answers to your latest set of questions:
-In the webconfig can i specify the groups that have access to each departmental page as well as the homepage? kinda like the following code, if so, i need my ldap connection string to be placed before assigning which groups have access to which page, right?
[Dipra] You are probably better off doing the authentication without using the roles in web.config, as this will also require the roles to be defined. We are talking about AD groups here, of which users will be a part. So, in the Page_Load(), simply call the authentication method, probably passing the username and the AD group allowed access to the page as parameters. If you want to make your solution configurable, store the allowed AD group for a particular page as 'keys' in your web.config and then read them in your code. Pass the group to your authentication method along with the username.
-when a user opens the web site, he will be prompted to insert his windows credentials, this is automatic, right? he will then be able to see the homepage and then go to his departmental page, right?
[Dipra] Yes, this is automatic. No separate code required for this. He can go to whichever page he wants, provided he is authenticated.
-if i understood correctly, in every page_load event i need to do a search taking the user's name and checking to which groups he belongs to, is that right?
[Dipra] Yes, you need to do that check in every Page_Load() method. As an approach, you can try getting all the groups of which the user is a part, and then check whether the allowed AD group for that page is one of those groups. If it is, the user can be authenticated.
-i the above is true, and now i'm gonna explain the navigation of the page 'cause i think that messing with the page_load might bring me some issues
will the check to see to which groups the user belongs to occur with every page load? won't that make the app slow?
[Dipra] Every server side control, e.g asp buttons, will cause a postback. To ensure the authentication code in Page_Load() doesn't run every time a postback happens on the page, enclose that bit in if(!Page.IsPostBack) {}. This means any code within this block will run when the page is not being 'posted back', i.e., being rendered for the first time. Any subsequent postbacks from server side controls on this page will ignore the code inside this block.
-finally, to check the membership of each user i need a similar code to the second answer on this The Link that Dipra posted i pasted below but in c#, right?
[Dipra] You can refer to the accepted answer on the above post, probably with a couple of tweaks of your own. It's already in C#.
Yes, your web.config would be like what you said.
You don't need to 'grant' access to specific groups for pages. In the web.config, store the groups allowed access to specific pages as keys and read the configuration in your code like this. For example, if you have a key named 'Marketing', then you can store the name of the corresponding AD group, which is allowed access to Marketing pages in the value field. Yes, once you have got it working for one page, others will be easier.
No, the authentication method that I talked about is a custom method you will write for yourself, which will use logic similar to the one in the link I had posted.
The entire authentication code should be enclosed in a try...catch block. If there are issues while doing the authentication against your AD (for e.g., connection problems), then your code will throw an exception. Catch (and ideally log) the exception and redirect the user to an error page, probably saying there were some problems which prevented authentication. You should not be granting access to the user in such a scenario.

Quickest way to require authentication in asp.net webform?

As of right now, I have the user register/log in and then if successful, redirect them to the homepage. However, this is extremely artificial as the user can simply type the url and go to any page they want. I'm fairly new to this and I've heard forms authentication mentioned multiple times as a way to do what I need: a simple means to prevent a user from accessing any page and once they haven't done a "Request" in awhile, I want them to be "logged out" and sent back to the log in page. I guess, in the end, I have three questions:
1) Can someone provide me a link to a great tutorial on authentication? I don't want to get too far in depth if I can avoid it.
2) Also, is it recommended to use cookies for this or not? I've heard different views on this?
3) I was told I can set this up in the web.config as well as in code behind? Is this true? If so, which do you recommend?
Thank you very much and I apologize for the broad question(s). If you need any more information, please let me know.
Here is Walkthrough: Creating a Website with Membership and User Logon that you can use.
As far as using cookies is concerned, they can be exploited. To be safe, its best not to put anything of value in them. If you have to, then you should secure them (another topic all together). In the scope of your question, know that ASP.NET encodes and hashes its authorization ticket so you are ok using the default cookie settings. More info on the Web.config form element attributes here.
Forms Authentication is setup in the Web.config file. You can set the slidingExpiration attribute to log a user out if they haven't made a request with in the time set in the attribute.
Take a look at this MSDN tutorial:
http://msdn.microsoft.com/en-us/library/ie/xdt4thhy.aspx
You can use the builtin asp.net sql membershiprovider and login controls for register and login this is implemented in the default web application project.
Then you can check the value of Request.IsAuthenticated in page load and redirect to login page with Response.Redirect(loginPageUrl)
1) http://www.asp.net/web-forms/overview/security good place to start.
2) If you are using the ASP.NET builtin authentication in most scenarios you dont have to worry about cookies. IMO nothing wrong with cookies :)
3) Usually you have to set this up in both. Generally you configure the auth method and the providers in web.config and do the redirection to login page in the codebehind or globally in global.asax.cs
Hope this helps.
Check How to: Implement Simple Forms Authentication.
This type of authentication requires a log-in form referenced in web.config. It can be done with or without cookie: Cookieless Forms Authentication.

Take down website to public, but leave for testing... "We're Not Open"

We are rolling out a site for a client using IIS tomorrow.
I am to take the site down to the general public (Sorry, we are updating message) and allow the client to test over the weekend after we perform the upgrade.
If it is successful, I open it to everbody - if not, I rollback.
What is the easiest way to put a "We're not open" sign for the general public, but leave the rest open to testers?
Redirect via IIS. Create a new website in IIS and put your "Sorry updating" message in the Default.aspx. Then switch ports between the real site (will go from 80, to something else (6666)) and the 'maintenance' site (set on 80).
Then tell your testers to go to yoursite.com:6666.
Then switch the real site back to 80 after taking down the 'maintenance' site.
I thought it would be worthwhile to mention ASP.NET 2.0+'s "app offline" feature. (Yes, I realize the questioner wants to leave the app up for testing, but I'm writing this for later readers who might come here with different needs).
If you really want to take the application offline for everyone (for instance to do server maintenance) there is a very simple option. All you have to do in ASP.NET 2.0 and higher is put a file with this name:
app_offline.htm
...in the root directory of your ASP.NET application. Put an appropriate "sorry come back later" message in there. That's it. The ASP.NET runtime does the rest.
Details on Scott Guthrie's blog.
Require that testers login. You can even hide the login page so that you need a direct link to even see it. Then, for all people not logged in, redirect to the page that displays your message.
Fire up another "site" in IIS which will catch your host-header for your primary site. Use either a custom 307/503/404 page that has "we're down for maintainance" or use some sort of URL-rewrite to redirect people to your single static file.
switch host-header-binding on your real site to something else, like dev.domain.com or testing.domain.com that your developers use.
Or, block by IP, and have your custom "Not authorized" page tell visitors that your down to maintainance.
You have several options.
Some methods that I've used before:
Windows authentication and/or separate subdomains for client to test.
Disable anonymous website access in IIS and give your client a username/password combo to test the website.
Disable default document in IIS and give your client an absolute URL to the main index file.
We tend to have a log in page and an include file across all pages in the site (usually the DB Connection as it's included in all files) that checks for a valid logged in session. If you've not logged in you get a message saying the site's down for maintainance

Path.GetTempFileName -- Directory name is invalid

Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account.
I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files.
I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet_regiis -i' and checked security on the folders etc. At this point I'm stuck.
Can anyone shed some light on this?
**Update:**Turns out that providing 'IUSR_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process.
This is probably a combination of impersonation and a mismatch of different authentication methods occurring.
There are many pieces; I'll try to go over them one by one.
Impersonation is a technique to "temporarily" switch the user account under which a thread is running. Essentially, the thread briefly gains the same rights and access -- no more, no less -- as the account that is being impersonated. As soon as the thread is done creating the web page, it "reverts" back to the original account and gets ready for the next call. This technique is used to access resources that only the user logged into your web site has access to. Hold onto the concept for a minute.
Now, by default ASP.NET runs a web site under a local account called ASPNET. Again, by default, only the ASPNET account and members of the Administrators group can write to that folder. Your temporary folder is under that account's purview. This is the second piece of the puzzle.
Impersonation doesn't happen on its own. It needs to be turn on intentionally in your web.config.
<identity impersonate="true" />
If the setting is missing or set to false, your code will execute pure and simply under the ASPNET account mentioned above. Given your error message, I'm positive that you have impersonation=true. There is nothing wrong with that! Impersonation has advantages and disadvantages that go beyond this discussion.
There is one question left: when you use impersonation, which account gets impersonated?
Unless you specify the account in the web.config (full syntax of the identity element here), the account impersonated is the one that the IIS handed over to ASP.NET. And that depends on how the user has authenticated (or not) into the site. That is your third and final piece.
The IUSR_ComputerName account is a low-rights account created by IIS. By default, this account is the account under which a web call runs if the user could not be authenticated. That is, the user comes in as an "anonymous".
In summary, this is what is happening to you:
Your user is trying to access the web site, and IIS could not authenticate the person for some reason. Because Anonymous access is ON, (or you would not see IUSRComputerName accessing the temp folder), IIS allows the user in anyway, but as a generic user. Your ASP.NET code runs and impersonates this generic IUSR___ComputerName "guest" account; only now the code doesn't have access to the things that the ASPNET account had access to, including its own temporary folder.
Granting IUSR_ComputerName WRITE access to the folder makes your symptoms go away.
But that just the symptoms. You need to review why is the person coming as "Anonymous/Guest"?
There are two likely scenarios:
a) You intended to use IIS for authentication, but the authentication settings in IIS for some of your servers are wrong.
In that case, you need to disable Anonymous access on those servers so that the usual authentication mechanisms take place. Note that you might still need to grant to your users access to that temporary folder, or use another folder instead, one to which your users already have access.
I have worked with this scenario many times, and quite frankly it gives you less headaches to forgo the Temp folder; create a dedicated folder in the server, set the proper permissions, and set its location in web.config.
b) You didn't want to authenticate people anyway, or you wanted to use ASP.NET Forms Authentication (which uses IIS's Anonymous access to bypass checks in IIS and lets ASP.NET handle the authentication directly)
This case is a bit more complicated.
You should go to IIS and disable all forms of authentication other than "Anonymous Access". Note that you can't do that in the developer's box, because the debugger needs Integrated Authentication to be enabled. So your debugging box will behave a bit different than the real server; just be aware of that.
Then, you need to decide whether you should turn impersonation OFF, or conversely, to specify the account to impersonate in the web.config. Do the first if your web server doesn't need outside resources (like a database). Do the latter if your web site does need to run under an account that has access to a database (or some other outside resource).
You have two more alternatives to specify the account to impersonate. One, you could go to IIS and change the "anonymous" account to be one with access to the resource instead of the one IIS manages for you. The second alternative is to stash the account and password encrypted in the registry. That step is a bit complicated and also goes beyond the scope of this discussion.
Good luck!
I encountered this error while diagnosing a console app that was writing in temp files. In one of my test iterations I purged all the files/directories in temp for a 'clean-slate' run. I resolved this self inflicted issue by logging out and back in again.
Could be because IIS_WPG does not have access to a temp folder. If you think it is a permission issue, run a Procmon on asp.net worker process and check for AccessDenied errors.
I was having the same problem with one of my ASP.Net applications. I was getting Path.GetTempPath() but it was throwing an exception of:
"Could not write to file "C:\Windows\Temp\somefilename", exception: Access to the path "C:\Windows\Temp\somefilename" is denied."
I tried a few suggestions on this page, but nothing helped.
In the end, I went onto the web server (IIS server) and changed permissions on the server's "C:\Windows\Temp" directory to give the "Everyone" user full read-write permissions.
And then, finally, the exception went away, and my users could download files from the application. Phew!
You can use Path.GetTempPath() to find out which directory to which it's trying to write.

Categories