Is making an asp:Button control invisible enough to be sure users won't be able to click it?

asp.net, authorization, c#, security, webforms

Solution

Yes, setting a button's `Visible` property to false is enough to prevent its `Click` and `Command` events from being raised, as long as you don't turn off the default WebForms security features.

You can easily test this by temporarily adding an always-visible `<input>` element to your .aspx with the same `name` as the rendered `<asp:Button>`:

<input type="submit"
       name="ctl00$ctl00$MainContent$LocalMainContent$FileList$ctrl0$ctl17"
       value="Fake Delete" />

Click the fake Delete button when the real Delete button is invisible. You should get an "Invalid postback or callback argument. Event validation is enabled..." exception.

Important notes:

- Don't set a button's `Visible` property to false within an `if (!IsPostBack)` block because it's possible for an attacker to bypass that check. See this answer for more information.

- ASP.NET event validation must be enabled (which it is by default). So don't turn it off by adding `EnableEventValidation="False"` to the `@Page` directive or `<pages enableEventValidation="false" />` to Web.config.

- Never ever ever disable view state validation by adding `EnableViewStateMac="False"` to the `@Page` directive or `<pages enableViewStateMac="false" />` to Web.config. This would allow an attacker to tamper with the hidden __EVENTVALIDATION field and do other nasty things.

- If you choose a derive a custom Button server control from the standard Button control, make sure you add the `[SupportsEventValidation]` attribute to the derived class.

- If you choose to create a custom Button server control from scratch, call `RegisterForEventValidation` and `ValidateEvent` in the appropriate places.

Problem

I'm making a simple website that lists files from a certain folder. If the user has admin rights, the user can delete files by clicking the "Delete" button. In my .aspx file, I have the following code: ``` <asp:Button runat="server" Text="Delete" OnCommand="FileList_Delete" CommandArgument='<%#Eval("FilePath")%>' Visible='<%CurrentUserIsAdmin()%>' /> ``` So the button will not be rendered if `CurrentUserIsAdmin()` returns `false`. The button is rendered like this: ``` <input type="submit" name="ctl00$ctl00$MainContent$LocalMainContent$FileList$ctrl0$ctl17" value="Delete" /> ``` My question is: Can I be sure that this method is safe against a known-code attack if the user modifies the webpage client-side aiming to click this invisible button? Or do I have to take precautions in the code-behind and verify the user's rights in the button-clicked event?

Original source