How we can prevent mass assignment

can anypne help me out with mass assignment vulnerability solution.


If I understand the description from wikipedia correctly, then this is mitigated by carefully aplying changesets.

1 Like

Hi Nobbz,

Thanks for reply. Can you please explain more about this solution.

Because You can specify what attributes are casted in a changeset, You can set attributes white list, which avoid mass assigment.

Also You can have multiple changesets, depending on what update You want to achieve.

So, no mass assigment problem :slight_smile:


Specifically the cast function is used to specify which data from an input should be added to the struct.

1 Like

@Abhishek14 To expand on what the others said - you probably have a def changeset function for your schema, which you explicitly call in your context functions - eg `

def create_post(attrs) do
    |> Post.changeset(attrs)
    |> Repo.insert()

But there’s nothing special about those names. You could have a admin_create_post/1 which calls Post.admin_changeset/2 and does different casting and validations, or a restricted_create_post/1 which calls Post.restricted_changeset/2, etc. You could call different changeset functions when creating and updating (or have your changeset/1 dispatch to different ones based on whether the record is persisted yet). It’s all up to you.

But basically, anytime you save data you get from a user, you should ensure that you pass the data through a changeset function which only accepts the data that the user should be allowed to give you.