C# 如何限制对WCF中某些方法的访问?

C# 如何限制对WCF中某些方法的访问?,c#,wcf,authentication,C#,Wcf,Authentication,开始使用简单的WCF服务时,我有点迷茫。我有两种方法,一种是向全世界公开,另一种是仅限于某些用户。最终,我希望能够使用客户端应用程序来使用受限方法。到目前为止,我可以匿名访问这两种方法: C#代码 namespace serviceSpace { [ServiceContract] interface ILocationService { [OperationContract] string GetLocation(string id);

开始使用简单的WCF服务时,我有点迷茫。我有两种方法,一种是向全世界公开,另一种是仅限于某些用户。最终,我希望能够使用客户端应用程序来使用受限方法。到目前为止,我可以匿名访问这两种方法:

C#代码

namespace serviceSpace
{
    [ServiceContract]
    interface ILocationService
    {
        [OperationContract]
        string GetLocation(string id);

        [OperationContract]
        string GetHiddenLocation(string id);
    }

    [AspNetCompatibilityRequirements(
     RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class LocationService : ILocationService
    {
        [WebGet(UriTemplate = "Location/{id}")]
        public string GetLocation(string id)
        {
            return "O hai, I'm available to everyone.";
        }

        // only use this if authorized somehow
        [WebGet(UriTemplate = "Location/hush/{id}")]
        public string GetHiddenLocation(string id)
        {
            return "O hai, I can only be seen by certain users.";
        }


    }
}
配置

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>    
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" 
          automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
</configuration>


如何开始?

使用以下步骤限制特定Windows用户的访问:

  • 打开计算机管理Windows小程序
  • 创建一个Windows组,其中包含要授予其访问权限的特定Windows用户。例如,一个组可以称为“CalculatorClient”
  • 将服务配置为需要ClientCredentialType=“Windows”。这将要求客户端使用Windows身份验证进行连接
  • 使用PrincipalPermission属性配置服务方法,以要求连接用户成为CalculatorClient组的成员

我找到的很多答案几乎都是我所需要的,但并不完全正确。最后,我设置了ASP.net成员身份,并实现了一个自定义属性,以便在请求传入时提取授权头并处理登录。所有的神奇都发生在下面的BeforeCall和ParseAuthorizationHeader中:


我认为这个问题的答案是一种可能的方法+1.谢谢你的代码。我尝试使用它,得到“System.ServiceModel.FaultException`1未经用户代码处理”,但我使用解决了它,现在它可以工作了。
// Only members of the CalculatorClients group can call this method.
[PrincipalPermission(SecurityAction.Demand, Role = "CalculatorClients")]
public double Add(double a, double b)
{ 
return a + b; 
}
public class UsernamePasswordAuthentication : Attribute, IOperationBehavior, IParameterInspector
{
    public void ApplyDispatchBehavior(OperationDescription operationDescription,
        DispatchOperation dispatchOperation)
    {
        dispatchOperation.ParameterInspectors.Add(this);
    }

    public void AfterCall(string operationName, object[] outputs,
                          object returnValue, object correlationState)
    {
    }

    public object BeforeCall(string operationName, object[] inputs)
    {
        var usernamePasswordString = parseAuthorizationHeader(WebOperationContext.Current.IncomingRequest);
        if (usernamePasswordString != null)
        {
            string[] usernamePasswordArray = usernamePasswordString.Split(new char[] { ':' });
            string username = usernamePasswordArray[0];
            string password = usernamePasswordArray[1];
            if ((username != null) && (password != null) && (Membership.ValidateUser(username, password)))
            {
                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), new string[0]);
                return null;
            }
        }

        // if we made it here the user is not authorized
        WebOperationContext.Current.OutgoingResponse.StatusCode =
            HttpStatusCode.Unauthorized;
        throw new WebFaultException<string>("Unauthorized", HttpStatusCode.Unauthorized);            
    }

    private string parseAuthorizationHeader(IncomingWebRequestContext request)
    {
        string rtnString = null;
        string authHeader = request.Headers["Authorization"];
        if (authHeader != null)
        {
            var authStr = authHeader.Trim();
            if (authStr.IndexOf("Basic", 0) == 0)
            {
                string encodedCredentials = authStr.Substring(6);
                byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                rtnString = new ASCIIEncoding().GetString(decodedBytes);
            }
        }
        return rtnString;
    }

    public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    public void Validate(OperationDescription operationDescription)
    {
    }

}
[ServiceContract]
interface ILocationService
{
    [OperationContract]
    string GetLocation(string id);

    [OperationContract]
    [UsernamePasswordAuthentication]  // this attribute will force authentication
    string GetHiddenLocation(string id);
}