我有在.NET Framework 4.6.2下运行的WCF服务。我之前曾使用web.config通过我的自定义IAuthorizationPolicy配置服务,如下所示:

<services>
behaviorConfiguration="MyClientService.CustomValidator_Behavior" name="My.Service.Implementation.Services.MyClientService">
        <endpoint binding="netHttpBinding" behaviorConfiguration="protoEndpointBehavior" address="BinaryHttpProto" bindingNamespace="http://My.ServiceContracts/2007/11" contract="My.ServiceContracts.IMyClientService" />
        <endpoint binding="netHttpsBinding" behaviorConfiguration="protoEndpointBehavior" address="BinaryHttpsProto" bindingNamespace="http://My.ServiceContracts/2007/11" contract="My.ServiceContracts.IMyClientService" />
        bindingConfiguration="netTcpCertificate" behaviorConfiguration="protoEndpointBehavior" bindingNamespace="http://My.ServiceContracts/2007/11" contract="My.ServiceContracts.IMyClientService" address="Sll"/>
        <host>
        </host>
      </service>
    </services>


    <behavior name="MyClientService.CustomValidator_Behavior">
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceMetadata httpGetEnabled="true" />
      <customBehaviorExtension_ClientService />
      <serviceThrottling maxConcurrentCalls="2000" maxConcurrentSessions="2147483647" maxConcurrentInstances="2000" />
      <serviceCredentials>
        <clientCertificate>
          <authentication certificateValidationMode="PeerOrChainTrust" />
        </clientCertificate>
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="My.Service.Implementation.Security.CustomUsernamePasswordValidator, My.Service.Implementation" />
      </serviceCredentials>
      <serviceAuthorization principalPermissionMode="Custom" serviceAuthorizationManagerType="My.Service.Implementation.Security.CustomServiceAuthorizationManager, My.Service.Implementation">
        <authorizationPolicies>
          <add policyType="My.Service.Implementation.Security.CustomAuthorizationPolicy_ClientService, My.Service.Implementation" />
        </authorizationPolicies>
      </serviceAuthorization>
    </behavior>

现在我需要通过代码来做到这一点,这看起来像:
var endpoint = new System.ServiceModel.Description.ServiceEndpoint(System.ServiceModel.Description.ContractDescription.GetContract(typeof(IMyClientService)),
                        binding,
                       new EndpointAddress(endPointAddress));

                endpoint.EndpointBehaviors.Add(new ProtoBuf.ServiceModel.ProtoEndpointBehavior());
                serviceHost.AddServiceEndpoint(endpoint);

                ServiceAuthorizationBehavior serviceAuthorizationBehavior = serviceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
                if (serviceAuthorizationBehavior == null)
                {
                    serviceAuthorizationBehavior = new ServiceAuthorizationBehavior();
                    serviceHost.Description.Behaviors.Add(serviceAuthorizationBehavior);
                }
                serviceAuthorizationBehavior.ExternalAuthorizationPolicies = new ReadOnlyCollection<IAuthorizationPolicy>(new IAuthorizationPolicy[] { new CustomAuthorizationPolicy_ClientService() });
                ((ServiceBehaviorAttribute)serviceHost.Description.Behaviors[typeof(ServiceBehaviorAttribute)]).MaxItemsInObjectGraph = 2147483647;
                ((ServiceBehaviorAttribute)serviceHost.Description.Behaviors[typeof(ServiceBehaviorAttribute)]).IncludeExceptionDetailInFaults = true;

                ServiceThrottlingBehavior throttleBehavior = new ServiceThrottlingBehavior
                {
                    MaxConcurrentCalls = 200,
                    MaxConcurrentInstances = 2147483647,
                    MaxConcurrentSessions = 2000,
                };
                serviceHost.Description.Behaviors.Add(throttleBehavior);

                Console.WriteLine("Starting service...");
                serviceHost.Open();
                Console.WriteLine("Service started successfully (" + uri + ")");
                return serviceHost;
            }
            catch(Exception ex)

在IAuthorizationPolicy中,我像以前一样设置原理,但在这里确实出错了:
var userContext = new UserContextOnService(new ClientIdentity { AuthenticationType = "regular", IsAuthenticated = true, Name = "username" }, currentAnvandare, LoginType.UsernamePassword);
            userContext.OrbitToken = orbitToken;
            evaluationContext.Properties["Principal"] = userContext;
            SharedContext.Instance.AddUserContext(person.PersonId.ToString(), userContext);

问题是当我尝试运行此命令时:

(UserContextOnService)Thread.CurrentPrincipal;

在我得到异常的服务方法中,CurrentPrincipal是的WindowPrincipal

我可以使用以下代码来获取正确的Principal:
OperationContext.Current.ServiceSecurityContext.AuthorizationContext.Properties["Principal"]

但这意味着要在许多仅使用Thread.CurrentPrincipal提取上下文的地方进行更改。

我怀疑我在配置中丢失了什么?

编辑:试图设置Thread.CurrentPrincipal = userContext;在Evaluate方法中,但这无济于事,如果Thread.CurrentPrincipal仍然是WindowsPrinciple?我怀疑服务方法最终在另一个线程上执行,然后执行评估。

最佳答案

启动服务时,还需要设置以下内容:

serviceAuthorizationBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
serviceAuthorizationBehavior.ServiceAuthorizationManager = new CustomServiceAuthorizationManager();

这是在以下行的上方完成的:
serviceAuthorizationBehavior.ExternalAuthorizationPolicies = new ReadOnlyCollection<IAuthorizationPolicy>(new IAuthorizationPolicy[] { new CustomAuthorizationPolicy_ClientService() });

08-04 12:50