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));
  }