недопустимое исключение mscorlib в пользовательском атрибуте безопасности c'tor - PullRequest
0 голосов
/ 06 июля 2011

Я пытаюсь реализовать свой собственный атрибут безопасности.Пока все очень просто

    [Serializable]
    [ComVisible(true)]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
    public class SecPermissionAttribute : CodeAccessSecurityAttribute
    {
        public SecPermissionAttribute(SecurityAction action) : base(action) { }

        public override System.Security.IPermission CreatePermission()
        {
            IPermission perm = new PrincipalPermission(PermissionState.Unrestricted);
            return perm;
        }
    }

По какой-то причине у меня есть исключение в атрибуте c'tor

System.IO.FileLoadException occurred
  Message=The given assembly name or codebase, 'C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll', was invalid.
  Source=WcfRoleProviderTestService
  StackTrace:
       at SecLib.SecPermissionAttribute..ctor(SecurityAction action)
       at WcfRoleProviderTestService.Service1.GetData(Int32 value) in D:\TestProjects\WcfRoleProviderTestService\WcfRoleProviderTestService\Service1.svc.cs:line 19
  InnerException: 

DLL подписана.Это кажется мне проблемой безопасности, но я не уверен.Кстати, я пытался использовать PrincipalPermissionAttribute, и он отлично работает.Забыл сказать, что я использую VS 2010, FW 4.0, атрибут в сервисе WCF продлен. Я буду очень рад получить помощь.

Моя конфигурация сервиса следующая

<system.web>
    <compilation debug="true" defaultLanguage="c#" targetFramework="4.0" />

    <roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES"
      defaultProvider="MyRoleProvider">
      <providers>
        <clear />
        <add connectionStringName="Service1" applicationName="InfraTest"
          writeExceptionsToEventLog="false" name="MyRoleProvider" type="SecLib.MyRoleProvider, SecLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=798c04e15cff851a" />
      </providers>
    </roleManager>

  </system.web>

<system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBindingConfiguration" closeTimeout="00:01:00"
          sendTimeout="00:10:00" maxBufferSize="524288" maxReceivedMessageSize="524288">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="WcfRoleProviderTestService.Service1"
               behaviorConfiguration="BasicHttpServiceBehavior" >
        <endpoint name="BasicHttpEndpoint"
                  contract="WcfRoleProviderTestService.IService1"
                  address="WcfAuthenticationTest"
                  binding="basicHttpBinding"
                  bindingConfiguration="BasicHttpBindingConfiguration" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/WcfRoleProviderTestService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="BasicHttpServiceBehavior">
          <serviceAuthorization principalPermissionMode="UseAspNetRoles"
            roleProviderName="MyRoleProvider" impersonateCallerForAllOperations="true" />
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

У меня ошибка как в Windows XP, IIS v5.1, так и в Windows Server 2008 R2 IISV7.5, только если служба WCF настроена для использования проверки подлинности Windows (см. Конфигурацию выше).Более интересным фактом является то, что ошибка возникла только в том случае, если атрибут используется с действием безопасности System.Security.Permissions.SecurityAction.Demand.

[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[SecPermission(System.Security.Permissions.SecurityAction.Demand)]
public string GetData(int value)
{
      string userName = ServiceSecurityContext.Current.WindowsIdentity.Name;
      return string.Format("You entered: {0}, User {1}", value, userName);
}

Другие параметры работают нормально.Спасибо.

1 Ответ

0 голосов
/ 17 июля 2011

С помощью одного из моих коллег проблема была устранена. Я не уверен, какова была точная причина исключения, но, похоже, это проблема компиляции. Когда я изменил тип проекта с веб-приложения на веб-сайт, который компилируется во время выполнения в соответствии с определением пула (64 или 32-разрядного), он начал работать нормально.

...