Friday, May 27, 2011

SharePoint 2010 - Buggy SPSecurityTrimmedControl and a workaround

Scenario:


The SPSecurityTrimmedControl control in SharePoint is incomplete and buggy.
Information about the bugs in this control are not provided by MSDN either.

In this post, I will try to explain the bug in the SPSecurityTrimmedControl and a solution to get over it.

Explanation:


The SPSecurityTrimmedControl  allows us to display/hide the content using a few different criteria, like authentication (for anonymous/authenticated users only), page mode (page in display or edit mode) or current user’s permissions.

So what's wrong?


The control doesn’t work the way you would expect it.
It does a good job with displaying content based on permissions but fails to conditionally display content based on authentication(anonymous/authenticated users).

That means using this control, you can hide an element from users who do not have the appropriate permissions.
Srini Sistla has a good post explaining all the available permissions here

This control also has the so called ability to show/hide content based on authentication(anonymous/authenticated users).

You would need to use the property "AuthenticationRestrictions" which can take any of these values:


  • AllUsers
  • AuthenticatedUsersOnly
  • AnonymousUsersOnly


For Ex:

<SharePoint:SPSecurityTrimmedControl runat="server" id="stc" AuthenticationRestrictions="AnonymousUsersOnly"> <p>User is not logged in</p></SharePoint:SPSecurityTrimmedControl>

In case if you try to use this control in the above manner, it wont give you the desired results.

Examine the below screenshots and you understand it better.

Test 1: Tried with "AnonymousUsersOnly"


I tried to access the page as an anonymous user and below is the output. So test failed


Test 2: Tried with "AuthenticatedUsersOnly"


I tried to access the page as an authenticated user and below is the output. So test passed


Solution:


The solution is to use the LoginView control if you need to show/hide content based on authentication.
The LoginView control provides the following templats:

  • AnonymousTemplate - Controls to show to anonymous users only
  • LoggedInTemplate - Controls to show to authenticated users only

Test 3: Tried both AnonymousTemplate & LoggedInTemplate

I tried to access the page as an authenticated user and below is the output. Test passed
I tried to access the page as an anonymous user and below is the output. So test passed



No comments:

Post a Comment