it:ad:asp.net:common:howto:urlauthorisationmodule:reference_code

IT:AD:ASP.NET:Common:HowTo:UrlAuthorisationModule/Reference Code

// Type: System.Web.Security.UrlAuthorizationModule
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll

using System;
using System.Runtime;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
using System.Web.Management;

namespace System.Web.Security
{
  /// <summary>
  /// Verifies that the user has permission to access the URL requested. This class cannot be inherited.
  /// </summary>
  public sealed class UrlAuthorizationModule : IHttpModule
  {
    private static bool s_EnabledDetermined;
    private static bool s_Enabled;
    private static GenericPrincipal _AnonUser;

    /// <summary>
    /// Creates an instance of the <see cref="T:System.Web.Security.UrlAuthorizationModule"/> class.
    /// </summary>
    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
    public UrlAuthorizationModule()
    {
    }

    /// <summary>
    /// Initializes the <see cref="T:System.Web.Security.UrlAuthorizationModule"/> object.
    /// </summary>
    /// <param name="app">The current <see cref="T:System.Web.HttpApplication"/> instance. </param>
    public void Init(HttpApplication app)
    {
      app.AuthorizeRequest += new EventHandler(this.OnEnter);
    }

    /// <summary>
    /// Releases all resources, other than memory, used by the <see cref="T:System.Web.Security.UrlAuthorizationModule"/>.
    /// </summary>
    public void Dispose()
    {
    }

    /// <summary>
    /// Determines whether the user has access to the requested file.
    /// </summary>
    /// 
    /// <returns>
    /// true if the current user can access the file; otherwise, false.
    /// </returns>
    /// <param name="virtualPath">The virtual path to the file.</param><param name="user">An <see cref="T:System.Security.Principal.IPrincipal"/> object representing the current user.</param><param name="verb">The HTTP verb used to make the request.</param><exception cref="T:System.ArgumentNullException"><paramref name="virtualPath"/> is null.- or -<paramref name="user"/> is null.- or -<paramref name="verb"/> is null.</exception><exception cref="T:System.ArgumentException"><paramref name="virtualPath"/> is outside of the application root path.</exception>
    [SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
    public static bool CheckUrlAccessForPrincipal(string virtualPath, IPrincipal user, string verb)
    {
      if (virtualPath == null)
        throw new ArgumentNullException("virtualPath");
      if (user == null)
        throw new ArgumentNullException("user");
      if (verb == null)
        throw new ArgumentNullException("verb");
      verb = verb.Trim();
      VirtualPath path = VirtualPath.Create(virtualPath);
      if (!path.IsWithinAppRoot)
        throw new ArgumentException(SR.GetString("Virtual_path_outside_application_not_supported"), "virtualPath");
      if (!UrlAuthorizationModule.s_EnabledDetermined)
      {
        if (!HttpRuntime.UseIntegratedPipeline)
        {
          HttpModulesSection httpModules = RuntimeConfig.GetConfig().HttpModules;
          int count = httpModules.Modules.Count;
          for (int index = 0; index < count; ++index)
          {
            if (Type.GetType(httpModules.Modules[index].Type, false) == typeof (UrlAuthorizationModule))
            {
              UrlAuthorizationModule.s_Enabled = true;
              break;
            }
          }
        }
        else
        {
          foreach (ModuleConfigurationInfo configurationInfo in HttpApplication.IntegratedModuleList)
          {
            if (Type.GetType(configurationInfo.Type, false) == typeof (UrlAuthorizationModule))
            {
              UrlAuthorizationModule.s_Enabled = true;
              break;
            }
          }
        }
        UrlAuthorizationModule.s_EnabledDetermined = true;
      }
      if (!UrlAuthorizationModule.s_Enabled)
        return true;
      AuthorizationSection authorization = RuntimeConfig.GetConfig(path).Authorization;
      if (!authorization.EveryoneAllowed)
        return authorization.IsUserAllowed(user, verb);
      else
        return true;
    }

    internal static void ReportUrlAuthorizationFailure(HttpContext context, object webEventSource)
    {
      context.Response.StatusCode = 401;
      UrlAuthorizationModule.WriteErrorMessage(context);
      if (context.User != null && context.User.Identity.IsAuthenticated)
        WebBaseEvent.RaiseSystemEvent(webEventSource, 4007);
      context.ApplicationInstance.CompleteRequest();
    }

    internal static bool RequestRequiresAuthorization(HttpContext context)
    {
      if (context.SkipAuthorization)
        return false;
      AuthorizationSection authorization = RuntimeConfig.GetConfig(context).Authorization;
      if (UrlAuthorizationModule._AnonUser == null)
        UrlAuthorizationModule._AnonUser = new GenericPrincipal((IIdentity) new GenericIdentity(string.Empty, string.Empty), new string[0]);
      return !authorization.IsUserAllowed((IPrincipal) UrlAuthorizationModule._AnonUser, context.Request.RequestType);
    }

    internal static bool IsUserAllowedToPath(HttpContext context, VirtualPath virtualPath)
    {
      AuthorizationSection authorization = RuntimeConfig.GetConfig(context, virtualPath).Authorization;
      if (!authorization.EveryoneAllowed)
        return authorization.IsUserAllowed(context.User, context.Request.RequestType);
      else
        return true;
    }

    private void OnEnter(object source, EventArgs eventArgs)
    {
      HttpContext context = ((HttpApplication) source).Context;
      if (context.SkipAuthorization)
      {
        if (context.User != null && context.User.Identity.IsAuthenticated)
          return;
        PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
      }
      else
      {
        AuthorizationSection authorization = RuntimeConfig.GetConfig(context).Authorization;
        if (!authorization.EveryoneAllowed && !authorization.IsUserAllowed(context.User, context.Request.RequestType))
        {
          UrlAuthorizationModule.ReportUrlAuthorizationFailure(context, (object) this);
        }
        else
        {
          if (context.User == null || !context.User.Identity.IsAuthenticated)
            PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
          WebBaseEvent.RaiseSystemEvent((object) this, 4003);
        }
      }
    }

    private static void WriteErrorMessage(HttpContext context)
    {
      context.Response.Write(UrlAuthFailedErrorFormatter.GetErrorText());
      context.Response.GenerateResponseHeadersForHandler();
    }
  }
}

  • /home/skysigal/public_html/data/pages/it/ad/asp.net/common/howto/urlauthorisationmodule/reference_code.txt
  • Last modified: 2023/11/04 02:42
  • by 127.0.0.1