Pages

Wednesday, June 16, 2010

ASP.NET Check if the current user can access a URL/Page

A method to verify that the user from the current HttpContext has sufficient roles to access a URL identified from the SiteMap.

  /// 
  /// Can the current User access the given URL according to the SiteMap (role trimmed)
  /// 
  /// URL to check. Can start with ~. Should not include query string parameters.
  /// True if the user has access.
  public static bool CanAccessUrl(string url)
  {
   SiteMapProvider provider = SiteMap.Provider;
   HttpContext current = HttpContext.Current;
   string rawUrl = VirtualPathUtility.ToAbsolute(url);
   SiteMapNode node = provider.FindSiteMapNode(rawUrl);
   return (node != null &&
    provider.IsAccessibleToUser(HttpContext.Current, node));
  }

2 comments:

  1. Replies
    1. I made it as a static method on a helper class. So I called it like:

      if(SecurityHelper.CanAccessUrl("~/SomeFolder/Default.aspx")) { \\ ... }

      Delete