WCF REST Authentication behavior

2019-06-13 05:45发布

问题:

I want to be able to authenticate a WCF Rest webservice but I'm not really sure how to go about it. It looks like many of the other questions relate to stuff in .net 3.5 WCF (such as WebServiceHost2) which no longer seems to exist.

I am wanting to do message based authentication on the WCF service with custom usernames and passwords. From what I can tell this can be done by the following in regular WCF:

<behaviors>
  <serviceBehaviors>
    <behavior name="PasswordValidator">
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="Custom"
                                customUserNamePasswordValidatorType="MyNamespace.PasswordValidator, MyNamespace"/>
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>

however as I am using Rest I cant get this web.config based behaviour config going. I somehow need to do this in my serviceRoute.

RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(HelloService)));

does anyone know how to do this or have any good tutorials on Message Based security with Rest and WCF 4.0?

回答1:

The way I solved this was to implement a custom authorize attribute which looks at two custom fields which I added into the HTTP headers collection.

This seems to work pretty well.

public class UserAndPasswordAuthenticationAttribute : 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)
        {
            string username = WebOperationContext.Current
                                   .IncomingRequest.Headers["username"];
            string password = WebOperationContext.Current
                                   .IncomingRequest.Headers["password"];


            if (username != "bob" || password!= "123")
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode =
                    HttpStatusCode.Unauthorized;
                throw new UnauthorizedAccessException("");
            }

            return null;
        }

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

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

        public void Validate(OperationDescription operationDescription)
        {
        }
    }

I can then just add this attribute to methods in my contract to secure them