Monthly Archives: November 2010

When SPSecurityTrimmedControl AuthenticationRestrictions FAILs, simple workaround

SPSecurityTrimmedControl is a nice offering by Microsoft when it comes showing and hiding parts of your page/web part/control depending upon user permissions.

In my case, I have the requirement to show some parts of my page only to anonymous users, and some only to logged in users, hence giving the illusion of different context for logged on and logged out users while staying on the same page. I was ready to take advantage of the AuthenticationRestrictions property until I found out that it doesnt work when I give it the value of AnonymousUsersOnly

This blog entry by Waldek Mastykarz mentioned this same problem. I figured that the SPSecurityTrimmedControl class is not sealed, yeeha… that means I can extend it to fix this broken feature. I work around this by adding my own property to the extension of SPSecurityTrimmedControl class, and overriding the Render method of this class.

Simply add this class to your project:

[ParseChildren(false), Designer(typeof(SPControlDesigner)), SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal), SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class SecurityTrimmer : SPSecurityTrimmedControl
{
    private bool _AnonymousOnly = false;

    public bool AnonymousOnly
    {
        get { return _AnonymousOnly; }
        set { _AnonymousOnly = value; }
    }

    [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
    protected override void Render(HtmlTextWriter output)
    {
        if ((!AnonymousOnly && HttpContext.Current.Request.IsAuthenticated) || (AnonymousOnly && !HttpContext.Current.Request.IsAuthenticated))
        {
            base.Render(output);
        }
    }
}

Then I use this within my page by replacing the SPSecurityTrimmedControl with my own control:

<%@ Register TagPrefix="myuc" Namespace="[[Your Namespace here]]" Assembly="[[Your Assembly Name here]]"%>

<!-- your other markup -->

<myuc:SecurityTrimmer id="SecurityTrimmedControl1" runat="server" AnonymousOnly="True">
   Text visible only to anonymous users
</myuc:SecurityTrimmer>

And Voila, it works!