Frage

I have a multitier system where all the business logic is available through WCF services.

Now consider the following scenario:

  1. a user opens my web application (ASP.NET MVC 4) and requests some entity from the WCF service
  2. the WCF service reads the entity from a database (using NHibernate)
  3. the entity goes through a security layer, where we find out that the user should not see some certain fields of this entity
  4. the presentation layer (doesn't matter, what it is - Web app, mobile app) generally should not be aware of the user's security rights. The presentation layer just takes every field it received from the service and renders it.

How do I strip the unnecessary information from the entity on the service and make my presentation layer unaware about those entity fields which the service did not want to return? What are the best practices to achieve this?

I guess, I should use DTOs (data transfer objects) but obviously I cannot define them strictly because I don't know which user has access to each field until the security layer (or some other field filtering system) kicks in.

War es hilfreich?

Lösung

While I can't claim that this is "best practice," this is at least one approach, taken by Rockford Lhotka in Expert C# 2008 Business Objects.

You could have all domain entities eventually derive from some base class. That base class could have a method like this:

public virtual bool CanReadProperty(string propertyName) { ... }

That method could be called by each property before allowing the user to view it (or set it). For better performance, that base class could have the authorization roles cached, so checking wasn't an expensive operation. And, of course now that we have expression trees, CanReadProperty() could take an expression so that it was strongly-typed.

An example of a property would look like this:

public string Name
{
    get
    {
        if (!CanReadProperty("Name")) { return string.Empty; } // or return null, whatever...
        return _name;
    }
}

The benefit of this approach is that you don't need many different DTOs for the various scenarios where the viewing of these properties can change.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top