Matthew James Davis
Matthew James Davis

Reputation: 12295

Selectively Serialize and Deserialize

I have a User object in my Linq-To-Sql mapping. There is a password attribute on it that I want to deserialize when submitted by a user--for example, during login. I never want to pass this attribute back to the user, though, since it will contain the encrypted version of the actual password and I'd rather not expose any information about the password or the encryption method. Is there a way to object-wide tell Linq-To-Sql to never pass the Password attribute when returning a User object?

Upvotes: 0

Views: 231

Answers (2)

Matthew James Davis
Matthew James Davis

Reputation: 12295

In the case where I never want to serialize an object, it is best to hook into the OnSerializing event. Since I'm using Linq-To-Sql, the OnSerializing event has already been captured by my DataContext's designer.cs for tracking serialization state for lazing loading entity references. Adding another function decorated with [OnSerializing] throws an error in System.ServiceModel.Activation, so I had to find another route. Here's my solution:

Modify DataContext.designer.cs

In DataContext.designer.cs, I added

[global::System.Runtime.Serialization.OnSerializingAttribute()]
[global::System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnSerializing(StreamingContext context)
{
    this.serializing = true;

    // custom function to handle my logic
    this.ClearPassword();
}

Add Method to my custom Class Definition

In my User.cs file, I have a partial class definition. Therefore, all I need to do is add the ClearPassword method to my partial class definition:

partial class User
{
    private void ClearPassword()
    {
        this.Password = null;
    }

    //* OTHER CODE *//
}

Now, no matter how I'm interacting with User objects, passwords are never passed to the client, as desired.

Upvotes: 0

Slack Shot
Slack Shot

Reputation: 1110

I use https for encryption, mostly because just in accessing the service, you by default enforce your encryption, which saves on client side code. You have a few possible answers though:

  1. Blank out the password when you return the User Object from the WCF side. (You can change the value of the password of the object, and just not save the change.. then return the object to the client )
  2. Use a custom object for your login response that returns only the necessary information for your client.
  3. Implement a Data Transfer Object pattern, with a nuget package like AutoMapper.

If you aren't salting and hashing your passwords, please please please consider it.

Upvotes: 2

Related Questions