Requiring Multiple Roles in Web.config Authorization - asp.net

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.

Related

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

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

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)
{ .......

ASP.Net: Login control, LoginUser_LoggedIn, and Role population

I have a forms based application. The application is standard ASP.Net wizard generated with login controls. The root's web.config appears to be in order for forms based authentication. I did have to change the <roleManager> element to use type="System.Web.Security.SqlRoleProvider" (rather than a Windows token) per How To: Use Role Manager in ASP.NET.
I have setup three roles - Administrators, Engineers, Customers. There are three users - admin (administrator), eddie (engineer), and cathy (customer). I have verified the users and their roles using ASP.Net Configuration Tool.
Each role has its own directory on disk, and each role has its own collection of ASPX files and 'landing page'. Each directory has a web.config to limit access to the role in question. For example:
<location path="~/Engineers">
<system.web>
<authorization>
<allow roles="Engineers" />
<deny users="*"/>
</authorization>
</system.web>
</location>
Upon successful login, I hook LoginUser_LoggedIn to write a destination URL. The problem I am having is the user's roles are not populated upon login, so I'm not getting a good redirect. In the code below, rolesArray has a zero size.
Any ideas? Should I be approaching this from a different angle?
Private Sub LoginUser_LoggedIn(sender As Object, e As System.EventArgs) Handles LoginUser.LoggedIn
Try
Dim rolesArray() As String
rolesArray = Roles.GetRolesForUser()
Debug.Assert(rolesArray.Length > 0)
If (Roles.IsUserInRole("Administrators") = True) Then
LoginUser.DestinationPageUrl = "~/Administrators/Dashboard.aspx"
ElseIf (Roles.IsUserInRole("Engineers") = True) Then
LoginUser.DestinationPageUrl = "~/Engineers/Workspace.aspx"
ElseIf (Roles.IsUserInRole("Customers") = True) Then
LoginUser.DestinationPageUrl = "~/Customers/Dashboard.aspx"
Else
Debug.Assert(False)
End If
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
The same request upon logging in, the cookie is not available for use (for instance, if you check this.User.Identity.IsAuthenticated, it returns false too). It's because the cookie is established during that request, and will be available upon subsequent requests.
I'd recommend redirecting to a common page, then doing this check and redirect again, or query the roles directly from the database using the user Id of the login control.

.ASPXROLES membership roles cookie expiry

Using ASP.NET 2.0, with forms authentication.
Just for a test, I configured the roles cookie in web.config like this :
<roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPXROLES" cookieTimeout="2"></roleManager>
I wanted to see what would happen when the cached role cookie expired.
Using Fiddler, after 2 minutes had elapsed, I could see that the raw value of the role cookie had changed.
I was expecting that on expiry, that ASP.NET would simply re-read the roles information from the database, and repopulate the cookie with the same value. So my question is, why would the raw value of the cookie change after expiry ? The cookie value is not human-readable (base 64 encoded and/or encrypted ?), so I can't tell if the information in it is the same, although the application still seems to work fine.
EDIT :
It looks like each time the roles are encrypted and cached in the cookie, it gets a different raw value.
e.g. if you run the following code :
RolePrincipal rp = (RolePrincipal) User;
string str = rp.ToEncryptedTicket();
Label1.Text = str;
You get a different value each time.
So the behavior seems normal.
Well the aspxroles cookie only pertains to role queries on the user. Unless you're doing things with the roles that would cause it to function differently (web.config auth?) then you're not going to see anything by expiring the cookie.
Can you share your web.config and basic pages that you're using to test this?
Have you tried that particular configuration to see what changes after the expiration?
<location path="img/logo.png">
<system.web>
<authorization>
<deny users="?"/>
<allow roles="CanSeeLogo"/>
</authorization>
</system.web>
</location>
Based on the question edit:
In my web.config under <configuration><system.web> I have this key:
<machineKey decryption="AES" decryptionKey="{64bits random hex}" validation="SHA1" validationKey="{128 bits random hex}"/>
I'm curious if you set that "manually" if you'll have a constantly changing encrypted string. Also, this is set by default in your C:\Windows\Microsoft.Net\Framework\etc folders, but you can redefine it (obviously) in your web.config to override it per application. This also allows you to share the same cookie cross-app within your domain.
Link to generate random hex strings
https://www.grc.com/passwords.htm
concat the first result from two page refreshes for the second one. Removing the web.config key later doesn't impact your app negatively (of course it wouldn't)

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