Flowing WCF Role-Based Security through to UI - wcf

I am looking for some best practices on how to handle the following scenario - flowing permissions from WCF service layer through to UI:
I have WCF services with methods that have been decorated with the PrincipalPermission attribute. I would like a means to allow a client to check if they have the required permissions before invoking the method.
A basic example of this could be checking whether a user can perform a specific function (say submitting an order), which can then be used to enable/disable a button within the UI.
Possible options are to add "chatty" operations like bool CanSubmitOrder() to the service, or instead have a single method OrderServicePermissions GetPermissions() which returns a message with a property CanSubmitOrder? I can then set the enabled state of a "Submit Order" button to the result.
So does anybody know of a better approach, or even a best practice?
Thanks in advance!

The whole point of having PrincipalPermission attributes on your service calls is that you don't have to check ahead of time whether or not the caller has the rights to call - if he doesn't, the WCF runtime will throw an exception.
Why not just rely on this built-in mechanism? Why not just put your service calls in a try..catch block and handle the exceptions if they do actually occur? It should be the "exceptional" case anyway, right?
I don't see any other "magic" way besides what you described. But the generally accepted practice would be to call and handle any exceptions if they occur.
Marc

Well, if you are able to evolve your applications to use Windows Identity Foundation (WIF) to secure your services you could achieve this using the DisplayToken property of the RequestSecurityTokenResponse.
http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.protocols.wstrust.requestsecuritytokenresponse.requesteddisplaytoken.aspx
Assuming your security token service supported it, the display token could contain a claim set that would allow you to flow your permissions into the UI, say to disable controls that are bound to services the user cannot call. The display token is an extension to WS-Trust that was implemented for CardSpace so it it not likely to be very widely supported outside of the Windows world.
Be aware though, that some people think the display token is bad news and violates the 1st law of identity:
http://www.francisshanahan.com
While other people think it is a reasonable and pragmatic solution to a common problem:
http://blogs.msdn.com/b/vbertocci/archive/2007/10/31/on-displaytoken.aspx

There are two general type to implement checking logic:
Share library. Example is "RIA Services + Silverlight".
Pluses: simple to implement.
Minuses: no interoperability (only .NET); required client update for every library changing.
Implement common method validation in service part.
Pluses: interoperability, no need for client update if checking logic changed
Minuses: may be to complex because it is only on you
If we use SOA it is better to use second choice, if only you are not using applications only in your company where .NET is everywhere.
Example
Let us consider common example. We have a windows/wpf form. And there are two fields: "surname" of type string, "age" of type int; and a button "Save". We need to implement some check on client side
1) for some users button "Save" is disabled;
2) surname cannot be empty and max length is 256;
3) age cannot be less than 0;
Invoking method to save is
void Save(string surname, int age);
Create second method in the service, which return object type of PermissonAnswerDTO with validation information;
PermissonAnswerDTO SaveValidate(string surname, int age);
and main validation method
// If arguments are wrong
[FaultContract(typeof(NotSupportedException))]
// If the user have permisson to invoke this method
[FaultContract(typeof(CustomNotEnoughPermission))]
PermissonAnswerDTO Validate(string methodName, object[] methodParams);
Validation.
Invoke Validate("SaveValidate", null) on window loading. If exception of type CustomNotEnoughPermission is throwed then we block "Save" button.
If user can save then invoke user's data Validate("SaveValidate", object[2]{"Surname", "-60"};. -60 is not valid so we get answer object of type PermissonAnswerDTO with information:
ParameterName: "age",
ExceptionMessage: "age cannot be less then null".
And we can gracefully show this information to user.
My thought on this is that some day Microsoft will implement this and call as new technology as it always does. Mostly Microsoft's technologies really are not so revolutionary as it is advertised. Examples are Windows Identity Foundation and Reactive Extensions.
Full example
[DataContract]
public class ParameterExceptionExplanaitonDTO
{
[DataMember]
public string ParameterName;
[DataMember]
public string ExceptionMessage;
}
[DataContract]
public class PermissonAnswerDTO
{
[DataMember]
public bool IsValid;
[DataMember]
public ParameterExceptionExplanaitonDTO[] ParameterExceptions;
}
public class Service1 : WcfContracts.IService1
{
// If arguments are wrong
[FaultContract(typeof(NotSupportedException))]
// If the user have permisson to invoke this method
[FaultContract(typeof(CustomNotEnoughPermission))]
public PermissonAnswerDTO Validate(string methodName, object[] methodParams)
{
//1) Using Reflection find the method with name = <methodName + Validate>
//2) Using Reflection cast each object in "object[] methodParams" to the required type
//3) Invoke method
}
private PermissonAnswerDTO GetUserNameValidate(int id)
{
//logic to check param
}
public string GetUserName(int id)
{
// if the user calls method we need validate parameter
GetUserNameValidate(id);
//some logic to retreive name
}
}

Related

Subtype of shared data contract

Following advices from people on the internet about service references, I got rid of them now and split the service/data contracts into a common assembly accesible by both the server and the client. Overall this seems to work really well.
However I’m running into problems when trying to use custom objects, or rather custom subtypes, in the service. Initially I wanted to define only interfaces in the common assembly as the contract for the data. I quickly learned that this won’t work though because the client needs a concrete class to instantiate objects when receiving objects from the service. So instead I used a simple class instead, basically like this:
// (defined in the common assembly)
public class TestObject
{
public string Value { get; set; }
}
Then in the service contract (interface), I have a method that returns such an object.
Now if I simply create such an object in the service implementation and return it, it works just fine. However I want to define a subtype of it in the service (or the underlying business logic), that defines a few more things (for example methods for database access, or just some methods that work on the objects).
So for simplicity, the subtype looks like this:
// (defined on the server)
public class DbTestObject : TestObject
{
public string Value { get; set; }
public DbTestObject(string val)
{
Value = val;
}
}
And in the service, instead of creating a TestObject, I create the subtype and return it:
public TestObject GetTestObject()
{
return new DbTestObject("foobar");
}
If I run this now, and make the client call GetTestObject, then I immediately get a CommunicationException with the following error text: “The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:09:59.9380000'.”
I already found out, that the reason for this is that the client does not know how to deserialize the DbTestObject. One solution would be to declare the base type with the KnownTypeAttribute to make it know about the subtype. But that would require the subtype to be moved into the common assembly, which is of course something I want to avoid, as I want the logic separated from the client.
Is there a way to tell the client to only use the TestObject type for deserialization; or would the solution for this be to use data transfer objects anyway?
As #Sixto Saez has pointed out, inheritance and WCF don't tend to go together very well. The reason is that inheritance belongs very much to the OO world and not the messaging passing world.
Having said that, if you are in control of both ends of the service, KnownType permits you to escape the constraints of message passing and leverage the benefits of inheritance. To avoid taking the dependency you can utilise the ability of the KnownTypeAttribute to take a method name, rather than a type parameter. This allows you to dynamically specify the known types at run time.
E.g.
[KnownType("GetKnownTestObjects")]
[DataContract]
public class TestObject
{
[DataMember]
public string Value { get; set; }
public static IEnumerable<Type> GetKnownTestObjects()
{
return Registry.GetKnown<TestObject>();
}
}
Using this technique, you can effectively invert the dependency.
Registry is a simple class that allows other assemblies to register types at run-time as being subtypes of the specified base class. This task can be performed when the application bootstraps itself and if you wish can be done, for instance, by reflecting across the types in the assembly(ies) containing your subtypes.
This achieves your goal of allowing subtypes to be handled correctly without the TestObject assembly needing to take a reference on the subtype assembly(ies).
I have used this technique successfully in 'closed loop' applications where both the client and server are controlled. You should note that this technique is a little slower because calls to your GetKnownTestObjects method have to be made repeatedly at both ends while serialising/deserialising. However, if you're prepared to live with this slight downside it is a fairly clean way of providing generic web services using WCF. It also eliminates the need for all those 'KnownTypeAttributes' specifying actual types.

WCF Soap webservice and authentication

I am creating a WCF service which uses basicHttpBinding(SOAP). I would like each request to the webservice to require an account name and a key, essentially a username and password. Currently these values are being passed as arguments to each exposed method. Is this the proper way to handle this situation? It seems to violate DRY, and I'm guessing that there is an easier, built in way. I have seen some examples of inserting a username and a password into the headers by intercepting the request but that approach seems to add quite a bit of effort for clients connecting.
Thanks!
Rather then sending the user name and password ever request, why not have a login method that returns a token, and pass that?
If you want to minimize DRY you can do the following:
First, make a generic class similar to the following that all request contracts inherit from (besides Login and Logout):
[MessageContract]
public abstract class AuthenticatedRequest <T> {
[MessageHeader]
public string Token { get; set;]
}
Now make a private function called private bool IsAuthenticated(string Token) that checks the token. This minimizes the ceremony of checking for authentication.

Request/Response pattern in SOA implementation

In some enterprise-like project (.NET, WCF) i saw that all service contracts accept a single Request parameter and always return Response:
[DataContract]
public class CustomerRequest : RequestBase {
[DataMember]
public long Id { get; set; }
}
[DataContract]
public class CustomerResponse : ResponseBase {
[DataMember]
public CustomerInfo Customer { get; set; }
}
where RequestBase/ResponseBase contain common stuff like ErrorCode, Context, etc. Bodies of both service methods and proxies are wrapped in try/catch, so the only way to check for errors is looking at ResponseBase.ErrorCode (which is enumeration).
I want to know how this technique is called and why it's better compared to passing what's needed as method parameters and using standard WCF context passing/faults mechanisms?
The pattern you are talking about is based on Contract First development. It is, however not necessary that you use the Error block pattern in WCF, you can still throw faultexceptions back to the client, instead of using the Error Xml block. The Error block has been used for a very long time and therefore, a lot of people are accustom to its use. Also, other platform developers (java for example) are not as familiar with faultExceptions, even though it is an industry standard.
http://docs.oasis-open.org/wsrf/wsrf-ws_base_faults-1.2-spec-os.pdf
The Request / Response pattern is very valuable in SOA (Service Oriented Architecture), and I would recommend using it rather than creating methods that take in parameters and pass back a value or object. You will see the benefits when you start creating your messages. As stated previously, they evolved from Contract First Development, where one would create the messages first using XSDs and generate your classes based on the XSDs. This process was used in classic web services to ensure all of your datatypes would serialize properly in SOAP. With the advent of WCF, the datacontractserializer is more intelligent and knows how to serialize types that would previously not serialize properly(e.g., ArrayLists, List, and so on).
The benefits of Request-Response Pattern are:
You can inherit all of your request and responses from base objects where you can maintain consistency for common properties (error block for example).
Web Services should by nature require as little documentation as possible. This pattern allows just that. Take for instance a method like public BusScheduleResponse GetBusScheduleByDateRange(BusDateRangeRequest request); The client will know by default what to pass in and what they are getting back, as well, when they build the request, they can see what is required and what is optional. Say this request has properties like Carriers [Flag Enum] (Required), StartDate(Required), EndDate(Required), PriceRange (optional), MinSeatsAvailable(Option), etc... you get the point.
When the user received the response, it can contain a lot more data than just the usual return object. Error block, Tracking information, whatever, use your imagination.
In the BusScheduleResponse Example, This could return Multiple Arrays of bus schedule information for multiple Carriers.
Hope this helps.
One word of caution. Don't get confused and think I am talking about generating your own [MessageContract]s. Your Requests and Responses are DataContracts. I just want to make sure I am not confusing you. No one should create their own MessageContracts in WCF, unless they have a really good reason to do so.

How to prevent 'Specified' properties being generated in WCF clients?

I have two .NET 3.5 WCF services build with VS2008.
I have two WCF clients in Silverlight to consume these services. The clients are generated with the 'Add Service Reference'. I am using Silverlight 4.
ONE of the proxies is generated with Specified properties for each property. This is a 'message-in' class for my service method :
// properties are generated for each of these fields
private long customerProfileIdField;
private bool customerProfileIdFieldSpecified;
private bool testEnvField;
private bool testEnvFieldSpecified;
Now my other service (still with a Silverlight client) does NOT generate Specified properties.
Now I don't care about 'tenets of good SOA'. I just want to get rid of these damn properties because in the context of what I'm doing I absolutely hate them.
There has to be some difference between the two services - but I don't want to have to completely rip them apart to find out the difference.
A similar question before had the answer 'you cant do it' - which is definitely not true because I have it - I just don't know what I did differently.
Edit: I am now in a situation where I regenerate my Silverlight 4 proxy to my 3.5 WCF service (all on the same localhost machine) that sometimes I get 'Specified' properties and sometimes I don't. I no longer think (as I suspected originally) that this is due solely to some endpoint configuration or service level [attribute]. Theres certain triggers in the message itself that cause Specified to be generated (or not). There may be many factors involved or it may be something very simple.
try this in your WCF service where the property is declared
[DataMember(IsRequired=true)]
public bool testEnvField { get; set; }
IsRequired=true will negate the need for the testEnvFieldSpecified property
These extra Specified properties are generated for value types which are being specified as optional in either the contract or the attribute markup.
As value types have a value by default, the extra Specified flags are being added for these properties, to allow the client (and server) to distinguish between something explicitly not specified or explicitly specified - which may well be set to the default value. Without it, integers would always end up being 0 (and being serialized) even if you don't set them (because of the mapping to int) in your client code. So when you do, you need to also make sure that you set the Specified flag to true, otherwise these properties will not get serialized.
So to prevent these flags being generated for value types, you would have to change the contract to make these value type properties mandatory, instead of optional.
Hope that makes sense.
OK I've found one thing so far that will cause Specified properties to be generated:
The presence of an XTypedElement in the message.
These are used by Linq2XSD. I was returning an element from a Linq2XSD model.
This triggered Specified properties to be generated EVERYTHING in all my classes :
public XTypedElement Foo { get; set; }
This however didn't :
public XElement Foo { get; set; }
Still curious as to why this is, and if there are any other things that trigger this.
NOTE: I realize this is an old question. I'm adding this here because this question comes up as a top result on Google, and it's helpful information for whoever comes looking.
Try adding this line into your operation contract declaration:
[XmlSerializerFormat]
It should look something like this:
namespace WebServiceContract
{
[ServiceContract(Namespace = "http://namespace")]
[XmlSerializerFormat] //This line here will cause it to serialize the "optional" parameters correctly, and not generate the extra
interface InterfaceName
{
/*...Your web service stuff here...*/
}
}
I found that if I put a DataTable in a service DataContract then the generated client will use xml serializer and thus generate the *IsSpecified members.

Web services and interface compatibility

Adding a service reference to a web service (this is all WCF) in Visual Studio produces some generated code including a client-side restatement of the interface being exposed.
I understand why this interface is generated: you might be consuming a 3rd party service and not have access to the actual interface.
But I do, and the two are not assignment compatible even though the transparent proxy does indeed exactly implement the interface to which I want to cast.
I can use reflection, but that's ugly. Is there some way to defeat this faux type safety and inject metadata to so I can use an interface with a class?
My specific problem departs from the norm in complicated ways that have to do with a single client that uses some derivatives of a base class directly and uses others remotely via service references. The base class for each server needs to keep references to subscribing clients in a collection for enumeration to notify events, and the problem was type varied due to the use of proxies.
None of these answers solves my specific problem, yet every single answer was instructive and helpful. I found my own solution (use a dual binding) but I would never have figured it out if you hadn't radically improved my understanding of the whole business.
Three excellent answers. How to choose just one? I choose the first, because it directly solves the problem I first thought I had.
If you already have the contract dll at the client, you don't even need a service reference (unless you are using it to write the setup code for you) - you can simply subclass ClientBase and expose the Channel, and use that directly - something like (no IDE handy...):
public class WcfClient<T> : ClientBase<T> where T : class
{
public new T Channel {get {return base.Channel;}}
}
Then you can just do things like:
using(var client = new WcfClient<IFoo>())
{
client.Channel.Bar(); // defined by IFoo
}
You still need the configuration settings in the config to determine the address, binding, etc - but less messy than proxy generation. Also, you might choose to re-implement IDipsoable to deal with the fact that WCF proxies can throw in Dispose() (which is bad):
public class WcfClient<T> : ClientBase<T>, IDisposable where T : class
{
public new T Channel {get {return base.Channel;}}
void IDisposable.Dispose() {
try {
switch(State) {
case CommunicationState.Open: Close(); break;
// etc
}
} catch {} // swallow it down (perhaps log it first)
}
}
When you add the service reference, go to "Advanced" and make sure "Reuse types in referenced assemblies" is selected and that the assembly containing your interface definition is selected. You can also do this with an existing service reference by right clicking on it and going to "Configure".
In order to return an interface from a service you need to use the KnownType attribute:
http://weblogs.asp.net/avnerk/archive/2006/07/31/WCF-Serialization-part-1_3A00_-Interfaces_2C00_-Base-classes-and-the-NetDataContractFormatSerializer.aspx
If you want to return a custom type from the service:
http://msdn.microsoft.com/en-us/library/bb628653.aspx
Does any of that help?