Getting the value of Request.ServerVariables(“LOGON_USER”) - asp.net

I'm trying to get authenticated username in my ASP.NET page using Request.ServerVariables(“LOGON_USER”) variable. It gives me an empty string. There are a lot of topics about this variable. The common point is using an authentication type other than None and denying anonymous access. So I added these lines in my web.config:
<authentication mode="Forms"/>
<authorization>
<deny users = "?" /> <!-- This denies access to the Anonymous user -->
<allow users ="*" /> <!-- This allows access to all users -->
</authorization>
I still get an empty string. How can I get the username?
Also tried:
Request.ServerVariables["REMOTE_USER"];
Request.ServerVariables["UNMAPPED_REMOTE_USER"];
Request.ServerVariables["AUTH_USER"];
HttpContext.Current.User.Identity.Name;

Finally fixed. You should disable anonymous access in IIS if you want to use Request.ServerVariables(“LOGON_USER”).
PS: Disabling anonymous access has some side effects such as infinite login redirect loop

Related

Redirect for some pages and deny access for others?

I'm using forms authentication.
In the root web.config there's ...
<authentication mode="Forms">
<forms loginUrl="~/Auth/Login.aspx" timeout="2880" defaultUrl="~/Search.aspx" />
</authentication>
... so if an unauthenticated user is denied access, by a entry like the following in the web.config of a subfolder ...
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
... then the not-logged-in user is redirected to the Login.aspx page.
First question
If an unauthenticated users requests some (but not all) pages, or requests files from one sub-folder (but not another), I want to deny access by returning HTTP 403 instead of redirecting them (HTTP 302) to the login page.
How can I do that? Currently unauthenticated users are invariably redirected to the Login page, instead of being simply denied access.
Second question
I'm also using 'role-based' privileges, for example I have a role named Supervisors.
Access to certain folders is intended only for supervisors so those folders have a web config like
<system.web>
<authorization>
<allow roles="Supervisor"/>
<deny users="*"/>
</authorization>
</system.web>
If an authenticated (logged-in) user without the Supervisor role attempts access, they too are redirected to the Login page (although they're already logged-in).
Can I change that, somehow (e.g. to return HTTP 403, or to redirect to some other failure page)?
You will have to do this manually by creating a Procedure which will run on Page_Init
Public Shared Sub CheckAccess()
If My.User.IsAuthenticated And (Condition Here) Then
Response.Redirect("AccessDenied.aspx")
End If
End Sub
Protected Sub Page_Init (sender As Object, e As EventArgs) Handles Me.PageInit
CheckAccess()
End Sub

ASP.Net authentication: Can I have multiple responses when user fails to authenticate/authorize to access a page

I am using ASP.net form authentication for my web application. I have folder "admin" for administration work, and also I can lock one user if he/she misbehaves.
currently if an normal user tries to access the admin page, it will be redirected to the logon page, although he/she is already logged on.
The question is: how can I configure the web app, so that when the user fails to access a page, I can show different pages such as "you need admin privilege to access this page"/"your account is locked out"/(normal logon page)?
ValidateUser() can only return bool. :(
Thanks a lot
You'll need to implement roles and add people to them. Once you assign people to the proper roles, you would check to see if the person is in the proper role to access a page. If not, redirect them or show the proper error message. You would be able to do this with code behind like it seems like you are already trying:
if(!Roles.IsUserInRole("Administrator")) Response.Redirect("~/");
Or you can use the web.config
<configuration>
<location path="memberPages">
<system.web>
<authorization>
<allow roles="Administrator" />
<deny users="*" />
</authorization>
</system.web>
</location>
<configuration>
See the links below for more info:
https://web.archive.org/web/20210417083524/https://www.4guysfromrolla.com/articles/121405-1.aspx
http://msdn.microsoft.com/en-us/library/ff647401.aspx
I solved this kind of problem giving different urls to diffenrent roles.
To admin you give www.yoursite.com/admin
to user you give www.yoursite.com/private
asp.net will automatically redirect both to the login.aspx page but you can get from the url parameter which kind of user it is.
//I detect where the request originated from
string str = Request.QueryString["ReturnUrl"] == null ? "" : Request.QueryString["ReturnUrl"].ToString();
//if this is Admin can access to Admin Area only
if (str.Contains("Admin") == true || str.Contains("admin") == true || str.Contains("ADMIN") == true)
{ .......

Requiring Multiple Roles in Web.config Authorization

Is it possible to specify that multiple roles are required inside the authorization element of the web.config file? I currently have this block in one web.config of my site for a specific directory:
<authorization>
<allow roles="Global, Region" />
<deny users="*" />
</authorization>
I've just identified a special case where a person with two lower-level permissions than Global and Region should also have access to this directory. Roughly, I want something like this:
<authorization>
<allow roles="GlobalManager, RegionManager, SiteManager && FooSite" />
<deny users="*" />
</authorization>
Any ideas? I realize I probably should have a new role for this scenario, but I'd like to avoid that. Thanks!
I don't think you can do this via the current configs allowed in web.config. What you could do though is something like the following... as the very first line in your Page_Load event for the page in question, use the following code (VB):
If Not (User.IsInRole("Role1") AndAlso User.IsInRole("Role2")) Then _
FormsAuthentication.RedirectToLoginPage()
This line of course is assuming you are using FormsAuthentication. If not, you would need to replace FormsAuthentication.RedirectToLoginPage() with the appropriate code depending on your authentication method.
I don't know your situation exactly, but based on your code, it looks like you could go one step further, and add a table with a mapping of users to sites, and do something like the following:
In a public module, add the following code:
<System.Runtime.CompilerServices.Extension()> _
Public Function ManagesSite(target As System.Security.Principal.IPrincipal, siteName As String) As Boolean
Return [ code here to look up whether this user can access the site specified ]
End Function
Then you can write the previous code as something more logical, such as:
If Not (User.IsInRole("SiteManager") AndAlso User.ManagesSite(Request.Url.Host)) Then _
FormsAuthentication.RedirectToLoginPage()
The method I usually use to solve this is when setting the user roles, create virtual roles. Therefore if the you wanted to only allow Student Administrators access to a page were a user has both Student and Administrator roles you could add a new StudentAdministrator role.

Sessions in asp.net

i have a login page so once the user enters the correct details he enters into the home page. Now i want to implement 3 things
once he clicks the button 'log out' he must be redirected to a page saying" logged out successfully " n even if clicks the back button in the browser, he should not be able to access.
if the user leaves the homepage idle for a specific amount of time say 10minutes and then he tries to navigate after 10 mins a msg should display saying "Your Session has been expired login again"
if given the url of homepage he shouldnt be able to access unless logged in.
I am not sure about what exactly i need to do and how to do. Plz Help
Regards
Indranil Mutsuddy
1) When the user logs out of the system I would recommend doing a Session.Abandon(). If the user clicks the Back button in the browser he might see the cached version of the old page (this is entirely browser dependant), but he won't be able to do anything anyway.
Disable the caching in your pages and the user shouldn't even see the cached old version :)
A simple way to do this would be to add the following into Global.asax's Application_BeginRequest:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
2) In your web.config set the session lifetim to 10 minutes, incremental.. That will do the trick
<system.web>
<authentication mode="Forms">
<forms defaultUrl="~/LoggedIn.aspx" loginUrl="~/Login.aspx" protection="All" path="/" slidingExpiration="true" timeout="10"/>
</authentication>
</system.web>
3) You can do this using authorization rules in web.config. If you want no anonymous users to access your website just enable access only to logged in users like this:
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
If you want to restrict access not to the whole website, but only to some areas (like the MyAccount area, then you can add this instead.. Note: Web.config can have multiple <location> elements!
<location path="MyAccountFolder">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
There's one important note about the location tag. The Path does NOW start with a '/'! So if you want to secure the /MyAccount folder, then your tag will start like this:
<location path="MyAccount" />
You should generally use ASP.NET Forms Authentication for this.
When the Log Out button is clicked, call FormsAuthentication.SignOut. This will remove the forms-authentication ticket information from the cookie (or URL if cookieless).
For a timeout, use the timeout attribute in the system.web/authentication/forms element of your web.config. Note that your forms authentication timeout is independent of your Session timeout.
Case 1:
When clicked on the log off button clear the Session.
Clicking the back button in the browser might result in fetching the page from the cache. So by cheking Session in the page might not be effective. You can disable caching for the page so that when back button is clicked a new request to the page will be generated.
For pages not to be cached set this
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Case 2:
You can set the default timeout for Session as 10 minutes. See HttpSessionState.Timeout Property
Case 3:
Check Session for null and if found to be null then redirect to a login page.

Does authorization in web.config check sub-groups as well?

If I put something like this in my ASP.NET web application's web.config:
<authorization>
<allow roles="MyUsers" />
<deny users="*" />
</authorization>
and then have an ActiveDirectory group SpecialGroup that is inside MyUsers, will a member of SpecialGroup be allowed to access my application?
Yes, it will. When you log on, a security token is constructed containing details of all¹ of the groups you're a member of, and that includes all nested groups. That token is what's used to determine access. This is why you have to log off and on when you're added to a group.
But just to be sure, I tested it on on of my sites and it worked as described.
¹ actually, it's possible to be in so many groups that they won't all fit in the token (which has a limited size) in which case, your token contains the first 'n' groups (which depends on the order returned by the domain controller, so you can see some odd behaviour).

Resources