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!

Advertisements

Posted on November 21, 2010, in Sharepoint and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: