开发者

ASP.NET: Role-based security and page design

I have a page with a couple of grids and a small form with 7 controls. The grids show ancillary data. Overall there are about 320 lines of code-behind that handle various events. I have the requirement that one particular role is only supposed to edit 3 fields out of the 7, whereas all other roles with access to this page can edit all of them.

Now to my question. We generally take the approach to restrict role-based security to the page level, since by doing that security in .Net becomes fully configurable开发者_运维百科. But in this case, I am about to make an exception because of this requirement, and this is new territory where I have no patterns. The amount of code duplication that I would have to do to create a separate page for the role with access to only 3 controls makes this not an option - even if I put some of the things into user controls, which seems an unjustifiable amount of work anyway.

My first thought was to disable all the controls in the page_load event that are not accessible for the current user, but that feels ugly. Is there a better way of doing this?


You could subclass the control types you want to protect, and determine in the OnLoad event whether to allow the user to edit.

public class ProtectedTextBox : TextBox
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        bool hasAccess = CurrentUserHasAccess(); // TODO
        if (hasAccess)
        {
            Enabled = true;
        }
        else
        {
            Enabled = false;
        }
    }
}

Then assign a prefix to the control in your web.config:

<pages>
    <controls>
        <add tagPrefix="me" Namespace="YourNamespace" assembly="YourAssembly" />
    </controls>
</pages>

Finally, just use it on your page in place of a regular TextBox for any field you want to prevent unauthorized users from modifying.

<me:ProtectedTextBox runat="server" <!-- etc. -->>

Do the same for Buttons as well as whatever other control types you need.


What if you made another form that also inherits from the same code behind file? Wouldn't that give you a different view and prevent you form duplicating code?


Can you arrange the controls so the ones that are effected by security are in a separate panel, then hide the panel based on security?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜