Anonymous user access in N2 CMS - Web Dev And Stuff
Tuesday, April 14, 2009 4:31 AM djsolid

Anonymous user access in N2 CMS


First of all i have to say that N2 CMS i a great Content Management System and really extensible! I discovered it a while ago and i decided to re-develop projects that were built with DotNetNuke with N2.

What do i want?

I want to show a page or a content only to anonymous users. I am using the default ASP.NET Role Provider for Sql Server.


So first of all i had to extend that provider. This is how :

public class MyCustomSqlRoleProvider : System.Web.Security.SqlRoleProvider
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        if (roleNames.Any(x => x == "Anonymous"))
            throw new InvalidOperationException("Cannot add \"Anonymous\" role
 to user(s). Role is automaticaly assigned.");
        base.AddUsersToRoles(usernames, roleNames);
    public override string[] GetAllRoles()
        List<string> roles = base.GetAllRoles().ToList();
        return roles.ToArray();
    public override bool IsUserInRole(string username, string roleName)
        if (HttpContext.Current != null && 
                   !HttpContext.Current.User.Identity.IsAuthenticated && 
                   HttpContext.Current.User.Identity.Name == username)
            return roleName == "Anonymous";
            return base.IsUserInRole(username, roleName);

Nothing fancy here. Just adding the Anonymous Role and checking if user is not logged in and the role being checked is “Anoynoumous” to return true. Also i try to ensure that no one will try to add the '”Anonoymous” role to a registered user.

Next i had to implement an ISecurityManager to do the Authorization. This is how :

public class MyCustomSecurityManager : N2.Security.SecurityManager
    public MyCustomSecurityManager(IWebContext webContext) : base(webContext) { }

public MyCustomSecurityManager(IWebContext webContext,

N2.Configuration.EditSection config) : base(webContext, config) { }

    public override bool IsAuthorized(ContentItem item, IPrincipal principal)
        bool isAuthorized = base.IsAuthorized(item, principal);
        if (!isAuthorized && !principal.Identity.IsAuthenticated && 
                      item.AuthorizedRoles.Count > 0)
            isAuthorized = item.AuthorizedRoles.Any(x => x.Role == "Anonymous");
        return isAuthorized;

Inheriting from N2.Security.SecurityManager i had to override only the IsAuthorized method to work the way i intended to.

And last but not least i had to add to the web.config the following

   <add service="N2.Security.ISecurityManager, N2"
     implementation="MyCustomSecurityManager, AssemblyName" />


I hope to find this post useful. If you have any suggestions or questions please let me know. And i case you haven’t checked N2 CMS just take a quick look.

kick it on

Filed under: , ,


No Comments