Have you ever had a client that wanted to do dynamic time of day IP filtering of a WCF service? No! What do you live under, a rock?
Well, I have and this is how I solved it. First, we look for better options like not writing code and use IIS IP Filtering. After that’s rejected by the client, I fire up my IDE; it takes so loooong.
publicclassIPFilteringAuthorizationManager:ServiceAuthorizationManager{privateconststringServiceActionAttempedBy="{0} Service Action {1} attemped by {2}.";privateconststringNoAuthorizedIPAddress="{0} is not an authorized IP address for {1}.";privateconststringAuthorizationManagerFailure="ARTServiceAuthorizationManager failure.";protectedoverrideboolCheckAccessCore(OperationContextoperationContext){varcallerIsAuthorized=false;varcallersIP=((RemoteEndpointMessageProperty)operationContext.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]).Address;varmesageTo=operationContext.RequestContext.RequestMessage.Headers.To.Segments.Last();varmessageAction=operationContext.RequestContext.RequestMessage.Headers.Action;try{callerIsAuthorized=GetAuthorizedIPAddresses(mesageTo).Contains(callersIP);if(!callerIsAuthorized){_log.Info(String.Format(NoAuthorizedIPAddress,callersIP,mesageTo));}}catch(Exceptionex){_log.Error(ex);}finally{_log.Info(String.Format(ServiceActionAttempedBy,mesageTo,messageAction,callersIP));}returncallerIsAuthorized;}}
I am a big fan of how WCF can be composed so I used a ServiceAuthorizationManager and added it to the services behaviors through the config.
I left out the boring part about which IP addresses are allowed and at what time, but I think you get the point. These dynamic rules for access to a WCF service can get a little sticky but WCF has some great extensibility points that allow you to solve your client’s problems. I have also used the same type of dynamic service authorization for use with Active Directory Groups.