April 11, 2006

CMS Logbook 4 - Setting default role for anonymous users

For anonymous users, I had to define a default role. Thus I would have fine grained control on what they can do in the cms site without declaring a Deny All grant. The first solution for such a thing is defining a default formsauthentication ticket for every anonymous request , that is speaking for ASP.NET 2.0 global.asax file ;


void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;

if (!app.Request.IsAuthenticated && app.Context.User == null)
{
FormsIdentity identity = new FormsIdentity(new
FormsAuthenticationTicket("anonymous", true, 5));
string role = "anonusers";

app.Context.User = new GenericPrincipal(identity,

new string[] { role }

);

}
}
This works but not a neat solution. I could not find a better solution on a built-in role definition for anon users so I have taken the following approach. In my CMS system all authorization requests are handled from a single business class , so I have changed it accordingly to define a default role for anon users, that is something like;
public
Authorizer():base()
{
SetupRoles(base.CurrentUser.Identity.Name);
}
public Authorizer(User user) : this(user.UserName)
{
}
public Authorizer(string username) : base()
{
SetupRoles(username);
}
private void SetupRoles(string username)
{
if (String.IsNullOrEmpty(username))
username = base.AnonymousUserName;
userroles = FindRolesOfUser(username);
}