How to get the windows login user on asp web page? - asp.net

I wonder if it is possible for an official way or hack to retrieve the windows login of the user currently logged on a asp web page with option "allow anonymous users" ? Or using imported windows dll perhaps ?
I know that normally with the "deny anonymous users" I can easily retrieve the login windows. But for some special reason I would like to retrieve the windows login and accept anonymous users. So that if the windows login is a user in my database I redirects to another web page.
I have ckecked that: (but windowsLogin == always empty)
ASP- C#
string windowsLogin = System.Security.Principal.WindowsPrincipal.Current.Identity.Name;
string windowsLogin = System.Threading.Thread.CurrentPrincipal.Identity.Name;
string windowsLogin = System.Net.CredentialCache.DefaultCredentials.ToString();
string windowsLogin = Request.ServerVariables["LOGON_USER"].ToString();
Web.config
<authorization>
<deny users ="?" /><!-- Deny acces to anonymous users-->
<allow users ="*" /><!-- Allow acces to every users-->
</authorization>
<identity impersonate="true"/>
<authentication mode="Forms">
<forms loginUrl="./WebLogin.aspx" defaultUrl="./default.aspx" timeout="12" path="/" name=".ASPXFORMSAUTH" slidingExpiration="true" />
</authentication>

You'll need to allow anonymous users, it seems, and you might want to try Windows authentication.
<authorization>
<allow users ="*" /><!-- Allow acces to every user and do not deny anonymous -->
</authorization>
<authentication mode="Windows" />
It seems ServerVariables have been depreciated for C# in some instances.
If so, you'll need to do it this way:
string login = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
If you really want to use ServerVariables, keep in mind they are CaSe Sensitive in C#. The correct casing is almost always UPPER, and here is the list of them:
List of ServerVariables

Related

Is IIS Form Authentication related anonymous authentication account?

Some resources (images) don't appear when I visit the main page after login (using form authentication)
However, setting the attribute of anonymous authentication to 'application pool id' in iis manager works
what windows account is used for form authentication in iis?
Only the login Page need anonymous authorization access. It sounds like you didn't set anonymous authentication correctly.
When we implement form authentication in IIS, Both form authentication and anonymous authentication are enabled side-by-side. Then we will create allow auth rule for all user and deny anonymous user in site level.
<authentication mode="Forms">
<forms name=".MyCookie" loginUrl="Login" protection="All" timeout="60" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
Secondly, we need to create a authorization rule to allow anonymous access to login page.
<location path="Login">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
When you pass the form authentication, IIS will send a form authentication cookie with the username which is decided by your application. It can be a key in appsetting or a username from database.
1.
FormsAuthentication.SetAuthCookie(UserInfo.UserName, false, FormsAuthentication.FormsCookiePath);
2.
FormsAuthenticationTicket
3.
FormsAuthentication.RedirectFromLoginPage(UserInfo.UserName, false);
You need to make sure the auth_user and application pool identity have permission to access the image sources.
https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp-net-applicatio

How can I have ASP.NET automatically redirect non-logged in Forms users to the login page?

I have an ASP.NET website.
I want users who are not logged in to be automatically (re)directed to the login page, for example,
~/Account/Login.aspx
As it is now, users are able to visit pages (for example, default.aspx) without being logged in.
Note: I am operating on the (perhaps incorrect) assumption that ASP.NET has its own authentication cycle that happens behind my back before every (and any) page loads.
Update #asawyer provided a link that, while not helping to answer the question, did provide a pretty graphic:
Well, what have you tried?
I have a web.config file that enables Forms authentication:
<?xml version="1.0"?>
...
<configuration>
...
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" name=".ASPXFORMSAUTH" slidingExpiration="true"/>
</authentication>
...
</system.web>
...
</configuration>
When i browse to the "default" page, I am able to view it, for example,
GET http://localhost:53149/WebSite/ HTTP/1.1
Host: localhost:53149
And I'm get the page contents:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
In other words, rather than being forced to login to the web-site, I am not being forced to log in to the web-site.
It might be related to the fact that my browser is running locally to the web-server; but I'm using Forms, not Windows (and not Passport and not None) authentication.
Bonus Reading
An Overview of Forms Authentication (C#)
MSDN: Forms Authentication Provider
MSDN: ASP.NET Web Application Security
ASP.NET Forms Authentication
Require the user to log in to view a document using ASP.NET
Protect some pages from direct access in ASP.NET
FormsAuthentication Class
I found the answer.
Question: How do I automatically redirect non-logged in users to the login page?
Answer: Deny anonymous users access
Longer Explanation
In order to automatically redirect non-logged in users to login page, you need to deny anonymous access to "all" pages. This is done in the site's web.config file:
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
...
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
The special ? token is used to represent anonymous users.
This, when combined with telling Forms authentication where the "Login" page is:
<?xml version="1.0"?>
<configuration>
<system.web>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
means that any any anonymous users will be automatically redirected to the login page.
A question that seems to never have been asked before gets answered, and everybody lives.
If you wish to force for all pages all used to be first logged in, you can capture the authentication request on global.asax and make this programmatically as:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// This is the page
string cTheFile = HttpContext.Current.Request.Path;
// Check if I am all ready on login page to avoid crash
if (!cTheFile.EndsWith("login.aspx"))
{
// Extract the form's authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
// If not logged in
if (null == authCookie)
// Alternative way of checking:
// if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Redirect("/login.aspx", true);
Response.End();
return;
}
}
}
This code is called on every page and checks all pages on your site.
I know it's many years later, but if anyone finds themself here you may be missing this bit in the webconfig. Within the tag you need to add this:
<location path="SecurePage.aspx">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
This tells the site that SecurePage.aspx requries the user to be logged in. This is how I've been doing it for a few years now
Add this to you web.config
<system.web>
// ...
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx"
name=".ASPXFORMSAUTH"
slidingExpiration="true" />
</authentication>
</system.web>

Prompting the user for login authentication

ASP.NET: I have created a website with login authentication. Before the user can visit any of the pages in it he needs to login first. How do I prompt the user to login first before he can view any of the contents of the website?
The Examining ASP.NET's Membership, Roles, and Profile series is a good starting point. It covers all the security part of ASP.NET and your required stuff, Login before visiting the page via LoginUrl as your login page. starting doing this How To: Use Forms Authentication with SQL Server in ASP.NET 2.0
Some setting to be made in web.config and then handle of these things on code behind.
<forms name=".ASPXAUTH" loginUrl="login.aspx"
defaultUrl="default.aspx" protection="All" timeout="30" path="/"
requireSSL="false" slidingExpiration="true"
cookieless="UseDeviceProfile" domain=""
enableCrossAppRedirects="false">
<credentials passwordFormat="SHA1" />
</forms>
Add the following element under the element in the Web.config file. This allows all authenticated users to access your Web site.
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>`
code behind
if (Membership.ValidateUser(username, password))
{
// User has supplied valid credentials
// In the following method call, the second Boolean parameter
// determines whether a persistent authentication cookie
// is created.
FormsAuthentication.RedirectFromLoginPage(username, rememberMeIsChecked);
}
Reference:
Starting ASP.NET Forms Authentication
ASP.NET Authentication
Explained: Forms Authentication in ASP.NET 2.0
Try to do this in your web.config
If we want to deny access to anonymous users, configure the Authorization section in the following manner,
<configuration>
<system.web>
<authentication mode="Forms"/>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
For more info look here
This is huge subject to cover on posting code example here so I would recommend following steps.
Use asp.net mvc3, learn how membership provider work, customize it if to fit your needs, user role provider to assign users to specific groups which you will use to protect specific area of site.
Create roles and assign them to user and after that you can secure pages using decorated [Authorize] attributes or secure for selected users like this
[Authorize(Roles = "Admin, Super User")]
Use your web.config in configuration system.web section to indicate what membership and role provider is used in app.
This is short info, but I hope that you have concise mental picture now.

Confusion about impersonation, authentication, and authorization in web.config

I'm trying to retrieve the windows login username for the current user in my asp.net website project.
my web.config file has the following items
<identity impersonate="true"/>
<authentication mode="Forms">
<forms name="app" path="/path" loginUrl="/path/login.aspx" protection="All" timeout="100" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*"/>
</authorization>
My understanding is that with this configuration I should be able to retrieve Domain\username from WindowsIdentity.GetCurrent().Name. However, this property returns NT AUTHORITY\IUSR which is the user for anonymous access. If I am not mistaken, I am denying anonymous access to the site in my authorization section. What am I missing?
Also of note:
System.Web.HttpContext.Current.Request.LogonUserIdentity.Name also returns NT AUTHORITY\IUSR and Request.ServerVariables["LOGON_USER"] returns an empty string, which goes against the information found in this KB article http://support.microsoft.com/kb/306359
I am using .net 4.0 and a windows 7 development environment.
Some resources that led me to this point:
http://msdn.microsoft.com/en-us/library/ff647076.aspx
http://support.microsoft.com/kb/306158
http://forums.asp.net/t/1121780.aspx/1?Getting+a+users+DOMAIN+username+from+a+web+application
Thanks for your time.
Edit
It should be noted that I am locked into forms authentication (windows authentication is not an option), as this is a multi tennant site, and the majority of users will not be using this single sign on feature.
If you're using forms authentication then impersonation is meaningless - it only works with Windows authentication. The same applies for Request.ServerVariables["LOGON_USER"].
The reason you're seeing IUSR_ is because that's the Windows account the web site is running as, instead you should use Page.CurrentUser (WebForms) or the User property (MVC Controllers), with no casting. This will return the Forms Auth username.

Authorization settings for a folder in ASP.NET

I have an asp.net web site, I want restrict all users to access a folder named "log" and I have this element in web.config:
<location path="log">
<system.web>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</location>
and this element before it in system.web:
<authorization>
<allow users="*"/>
</authorization>
but still I have access to this url: http://www.mydomain.com/log/log.txt
Any ideas?
Thanks.
.txt files are not handled by ASP.NET by default. You'll have to block access to the folder from within IIS.
If you're using IIS 7 you can use Request Filtering to achieve this.
to avoid this confusions I usually create one web.config file at the directories i need to set different permissions.
If you place a web.config file inside your log folder it will work ok (and it will become easier to check the applied permissions at the folder)
Example:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
I typed up a summary since many were facing the same situation regarding subfolder authentication.
Subfolder Authorization
ASP.NET can only have a single
authentication mode for one
application.
The different
applications CANNOT share resource
among them.
Scenario
Let's say the home page should not prompt login dialog. It should let users pass through without whatever login is. However, in the same applicatiopn, in a different folder presumably, another page needs to check user permission against database table using user network login ID. By default IE treats all web site with only hostname a Intranet. By its default intranet setting, it will not prompt the login dialog and pass user login and password to the application if Windows Authentication is used. However, the tricky party is, if the application has an actual domain, IE will think it is an Internet site, and it will prompt the login and password if Windows Authentication is used.
The only way to not to promopt login dialog for Internet site using Windows Authentication, is to also turn on the anonymous authentication in IIS. However, you will lose the ability to capture the login info because the Anonymous has precedence over the Windows Authentication. The good news is there is a way to resolve that issue. If an application subfolder needs to capture the login information, you will need to overwrite the parent authorization in Location element in web.config.
1 In IIS, configure Authentication as follows:
Enable Anonymous Authentication,
Enable Windows Authentication
2 Add the followings in Web.Config.
<authentication mode="Windows" />
<authorization>
<allow users="*" />
</authorization>
<!-- secured is the relative subfolder name. deny anonymous user, so only the authenticated login will pass through -->
<location path="secured" allowOverride="true">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>

Resources