淘先锋技术网

首页 1 2 3 4 5 6 7

WCSF的实现方法

WCSF通过 EnterpriseLibraryAuthorizationService 来实现“user -> role -> rule -> web url”的授权机制,相关的代码如下:

  • 注册服务(Shell 工程的 ShellModuleInitializer.cs 文件)
    代码
    1  protected   virtual   void  AddGlobalServices(IServiceCollection globalServices)
    2          {
    3              globalServices.AddNew < EnterpriseLibraryAuthorizationService, IAuthorizationService > ();
    4              ...
    5          }

     

  • 实现服务(内部注册并实现了 Web 应用程序的 AuthorizeRequest 事件处理)
    代码
     1  public   void  Init(HttpApplication httpApplication)
     2  {
     3     ICompositionContainer rootContainer  =  httpApplication.Application[ApplicationConstants.RootContainer]  as  ICompositionContainer;
     4      if  (rootContainer  !=   null )
     5     {
     6        httpApplication.AuthorizeRequest  +=   delegate ( object  sender, EventArgs e)
     7        {
     8           IHttpContext context  =   new  Microsoft.Practices.CompositeWeb.Web.HttpContext(httpApplication.Context);
     9           HandleAuthorization(rootContainer, context);
    10        };
    11     }
    12  }
    13   
    14  protected   virtual   void  HandleAuthorization(ICompositionContainer rootContainer, IHttpContext context)
    15  {
    16      if  (context.SkipAuthorization)  return ;
    17     IAuthorizationRulesService authorizationRulesService  =  rootContainer.Services.Get < IAuthorizationRulesService > ();
    18     IVirtualPathUtilityService virtualPathUtility  =  rootContainer.Services.Get < IVirtualPathUtilityService > ();
    19      if  (authorizationRulesService  ==   null return ;
    20      string [] rules  =  authorizationRulesService.GetAuthorizationRules(virtualPathUtility.ToAppRelative(context.Request.Path));
    21      if  (rules  ==   null   ||  rules.Length  ==   0 return ;
    22   
    23     IAuthorizationService authorizationService  =  rootContainer.Services.Get < IAuthorizationService > ( true );
    24      foreach  ( string  rule  in  rules)
    25     {
    26         if  ( ! authorizationService.IsAuthorized(rule))
    27           {
    28               throw   new  HttpException( 403 , Properties.Resources.UserDoesntHaveAccessToTheRequestedResource);
    29           }
    30     }
    31  }
    32 

     

自定义实现方法

  • 实现自定义的验证逻辑
  • 注册自定义服务

    代码
    1  protected   virtual   void  AddGlobalServices(IServiceCollection globalServices)
    2  {
    3     globalServices.AddNew < CustomAuthorizationService, IAuthorizationService > ();
    4   
    5      //  globalServices.AddNew<EnterpriseLibraryAuthorizationService, IAuthorizationService>();
    6     ...
    7  }
    8 

     

转载于:https://www.cnblogs.com/csharpstyle/archive/2010/04/26/1721212.html