May 28, 2006

CMS Logbook 5 - Setting default role for anonymous users (part 2)

First of all, this is valid for asp.net only.
Here's the situation, I have some business logic that needs authorization. Yet the not logged in users should have some access defined with the role 'anonusers'. The problem is how the business logic (a seperate class library) gets the authentication info. As this is a web site with Forms Authentication I used HttpContext.Current field to get the authenticated user.

The business logic , uses a base class property namely CurrentUser to get the current user authenticated:


public IPrincipal CurrentUser
{
get
{
if (HttpContext.Current !=
null)
return HttpContext.Current.User;
else
{
GenericIdentity
defaultIdentity = new GenericIdentity("anonymous");
string[] roles = new
string[1];
roles[0] = "anonusers";
GenericPrincipal genericPrincipal
=
new GenericPrincipal(defaultIdentity, roles);
return
genericPrincipal;
}
}
}

As you see if there is no user found in the context, this returns a 'anonymous' principal.

By this way I can now unit test all the business logic.

No comments:

Post a Comment