Search code examples
asp.net-mvcmvcsitemapprovider

Security Trimmings with MVCSiteMapProvider


When using Security Trimmings with the MVCSiteMapProvider is there a way to hide a node when the user is authenticated, but show it when they are not authenticated (opposite to the way one normally uses it)?

Say I have a menu that shows Register, Sign-In, and Support. When authenticated, I'd like it to hide Register and Sign-In, replacing with say, My Account, and then continue to show Support. So, trying to stick with the Security Trimming features of the MVCSiteMapProvider, I'd like to hide a node when authenticated.

Thanks muchly!


Solution

  • The easiest way is to use a custom visibility provider to hide the node when the user is authenticated. The MVC Music Store demo has an example of this.

    /// <summary>
    /// Only displays nodes when a user is not authenticated.
    /// </summary>
    public class NonAuthenticatedVisibilityProvider
        : SiteMapNodeVisibilityProviderBase
    {
        #region ISiteMapNodeVisibilityProvider Members
    
        /// <summary>
        /// Determines whether the node is visible.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="sourceMetadata">The source metadata.</param>
        /// <returns>
        ///     <c>true</c> if the specified node is visible; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsVisible(ISiteMapNode node, IDictionary<string, object> sourceMetadata)
        {
            return !HttpContext.Current.Request.IsAuthenticated;
        }
    
        #endregion
    }
    

    You can call it by specifying the assembly type in the visibilityProvider property/attribute of the nodes you want to use it.

    <mvcSiteMapNode title="$resources:SiteMapLocalizations,LogOnTitle" action="LogOn" visibilityProvider="MvcMusicStore.Code.NonAuthenticatedVisibilityProvider, Mvc Music Store" />