DR913
DR913

Reputation: 129

ASP.NET Model Protection

I have a new-ish developer on staff who is creating models with a sort of interface variable to "protect" other variables. The code kinda looks like this:

public class stuff
{
   public int id { get; set; }
   public string name { get; set; }
   public int thingType { get; set; }
}
public class people
{
   public int id { get; set; }
   public sting name { get; set; }
   private IEnumerable<stuff> ourThings;
   public IEnumerable<stuff> things { get {return ourThings; } }
}

I assumed that if I didn't want to risk someone modifying a model, I would make my set method for those variables private. I'm also not aware of how this can influence\prevent an attack on my site. Has anyone ever seen or heard of this before? If so, can you explain what the purpose really is and what I am trying to protect?

Thanks again!

Upvotes: 1

Views: 62

Answers (2)

Paul Keister
Paul Keister

Reputation: 13077

Public, internal, and private access modifiers are used to enforce constraints on your application architecture, they aren't intended as a defense against attacks.

I'd recommend you seek out guidance on how to secure web applications. There are plenty of materials available on this topic.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Well the overall problem with this entire thing:

private IEnumerable<stuff> ourThings;
public IEnumerable<stuff> things { get {return ourThings; } }

is that the collection can still be modified. You don't need a set to modify a collection because it's a reference type. But, if you wanted to make it immutable by design you might do something like this:

private IEnumerable<stuff> ourThings;
public IEnumerable<stuff> things { get {return ourThings.ToList(); } }

because that will build a copy of the original collection. That's one way of doing it anyway, and it proves to be pretty successful.

Upvotes: 3

Related Questions