Authentication, Authorization, User and Role Management and general Security in .NET

For coarse-grained security, you might find the inbuilt principal code useful; the user object (and their roles) are controlled in .NET by the “principal”, but usefully the runtime itself can enforce this. The implementation of a principal can be implementation-defined, and you can usually inject your own; for example in WCF. To see the runtime … Read more

Can I hide/show asp:Menu items based on role?

You can remove unwanted menu items in Page_Load, like this: protected void Page_Load(object sender, EventArgs e) { if (!Roles.IsUserInRole(“Admin”)) { MenuItemCollection menuItems = mTopMenu.Items; MenuItem adminItem = new MenuItem(); foreach (MenuItem menuItem in menuItems) { if (menuItem.Text == “Roles”) adminItem = menuItem; } menuItems.Remove(adminItem); } } I’m sure there’s a neater way to find the … Read more

asp.net mvc decorate [Authorize()] with multiple enums

Here is a simple and elegant solution which allows you to simply use the following syntax: [AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)] When creating your own attribute, use the params keyword in your constructor: public class AuthorizeRoles : AuthorizeAttribute { public AuthorizeRoles(params MyEnum[] roles) { … } protected override bool AuthorizeCore(HttpContextBase httpContext) { … } } This will allow … Read more

How do I serve up an Unauthorized page when a user is not in the Authorized Roles?

Add something like this to your web.config: <customErrors mode=”On” defaultRedirect=”~/Login”> <error statusCode=”401″ redirect=”~/Unauthorized” /> <error statusCode=”404″ redirect=”~/PageNotFound” /> </customErrors> You should obviously create the /PageNotFound and /Unauthorized routes, actions and views. EDIT: I’m sorry, I apparently didn’t understand the problem thoroughly. The problem is that when the AuthorizeAttribute filter is executed, it decides that the … Read more