Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / WCF

How to Implement Custom Role Based Authorization for My WCF Service Operations

13 Feb 2014CPOL 14.1K  
How to implement custom role based authorization for my WCF service operations

You can use custom attributes to implement it. Create a new custom attribute as below:

CustomMembershipAuthorization.cs

C#
public class CustomMembershipAuthorization : Attribute, IOperationBehavior, IParameterInspector
{
    public string AllowedRole { get; set; }

    public CustomMembershipAuthorization()
    {
    }

    public CustomMembershipAuthorization(string allowedRole)
    {
        AllowedRole = allowedRole;
    }

    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)
    {
        if (!Thread.CurrentPrincipal.IsInRole(AllowedRole))
        {
            if (WebOperationContext.Current != null)
                WebOperationContext.Current.OutgoingResponse.StatusCode =
                                                      HttpStatusCode.Unauthorized;

            throw new WebFaultException<string>("Unauthorized", HttpStatusCode.Unauthorized);
        }

        return null;
    }

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

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

    public void Validate(OperationDescription operationDescription)
    {
    }

}

Use the above defined custom attribute with your operation contract as below:

C#
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        [CustomMembershipAuthorization("client")]
        bool Log(MyLog req);

        [OperationContract]
        [CustomMembershipAuthorization("admin")]
        MyLog GetLog(string logId);
     }
}

In the BeforeCall() method of the CustomMembershipAuthorization class, you can modify the code as per your requirement. Here, you can verify if the user belongs to the role which is allowed to access the operation.

Please refer to How to implement simple custom membership provider for details of how to authenticate the user using custom username and password.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)