You can use custom attributes to implement it. Create a new custom attribute as below:
CustomMembershipAuthorization.cs
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:
[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.