开发者

WCF Dataservice - modify object before returning results?

I am using WCF data services and I have a few fields/properties that I want to "blank out" (set value to empty string or null) before sending back to client.

For example: User tabl开发者_JS百科e has password column which I do not want to pass the value to the client. This is one example, there are other such columns in the app that the value should be excluded for security/privacy reasons.

Sorry for such a basic question, I'm new to WCF dataservices and have not found any promising leads yet. I've tried QueryInterceptors but no luck.

Can someone point me in the right direction?

Thanks


IMO this is out of scope of WCF Data Services. WCF Data Services are meant to take your entity model and expose it as is based on access rules. If your entity exposes some properties and that entity is exposed its properties are simply public. It is for simple CRUD scenarios or read-only scenarios.

QueryInterceptor will not help you because it can be used for data driven authorization - it means that QueryInterceptor can add some additional condition to filter records which current user is not permitted to see = it will filter out whole records but it will not modify filtered result.

There is no hook to null fields because that is a bad approach. If you don't want expose some fields they should not be part of exposed entity at all. You can create second read-only entity exposing only public fields by using QueryView in your EDMX file. Next you need to modify access rules in your DataServiceConfiguration. You must remove access rule to initial User entity set and add read access rules to that new entity set.

If you need to control access rules per user you have to use some kind of authentication in your service and you must handle this in InitializeService method (unless DataServiceConfiguration is available elsewhere). Something like:

public static void InitializeService(DataServiceConfiguration config)
{
    var context = ServiceSecurityContext.Current;
    if (context != null && context.PrimaryIdentity != null)
    {
        var userName = context.PrimaryIdentity.Name;
        if (SomeMethodToValidateUserPermissions(userName)
        {
            config.SetEntitySetAccessRule("Users", EntitySetRights.AllRead);
        }
    }

    config.SetEntitySetAccessRule("TrimmedUsers", EntitySetRights.AllRead);
} 

By going more deep into WCF there can be other approaches to restrict access to some resources but this one is simplest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜