We have found what appears to be a “bug” in the permissions model for the SPWeb object, or something which functions in a way contrary to what would logically be expected.
Summary
If a Domain Group has been added in to any role for a web, and a user in that domain group visits the site, the user will still be returned as part of SPWeb.AllUsers even if the domain group is removed completely from the site.
Workaround
If you need to ensure that each user in the AllUsers list have permissions to the web, you can use the DoesUserHavePermissions method of the SPWeb object.
Details
Take for example the following scenario: You decide to grant all of your domain users “viewer” access to your web. You place Domain\Domain Users into the built-in “Viewers” group in your web. Mary Johnson is a member of Domain\Domain Users.
Mary Johnson then visits your web. A few days later, you realize you don’t want all domain users to view your web, so you remove Domain\Domain Users from your web completely, even from your Site Collection (“Site”).
In custom code (for example, a custom web part), you reference an instance of the current SPWeb object, and call the AllUsers property – this property will return the SPUser object for Mary Johnson even though she should no longer have permissions in this web.
To work around this issue, loop through each user in the AllUsers collection, and individually check their permissions. You can use the SPBasePermissions enumeration to choose which level of permissions you would like to check for.
Example:
SPWeb currentWeb = SPContext.Current.Web;
foreach (SPUser test in currentWeb.AllUsers)
{
bool userIsValid = currentWeb.DoesUserHavePermissions( test.LoginName, SPBasePermissions.ViewPages);
// Do something if user is valid
}
Notes
When you add your domain group, at first you will only see the entry for the domain group itself on the People and Groups page (http://<your_web_url>/_layouts/people.aspx). Once a user in the domain group visits the site, this person will now also appear in the All People list (in addition to the domain group). It appears that the user’s information is copied into the site once they visit a web for the first time – thus the user is being referenced by the AllUsers collection.