views:

1356

answers:

1

I want to user Role based security through the authorization section in the web.config file.

Using Membership, my application will allow for new Roles to be created, and thus, the pages they can access need to be set dynamically.

Can I programatically alter this section in the web.config to manage this? If so, how?

+4  A: 

Try:

//C#
using System.Configuration;
using System.Web.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AuthorizationSection section = (AuthorizationSection)config.GetSection("system.web/authorization");

AuthorizationRule rule = new AuthorizationRule(AuthorizationRuleAction.Allow);
rule.Roles.Add("admins");
section.Rules.Add(rule);

config.Save();

//VB
Imports System.Configuration
Imports System.Web.Configuration

Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim section As AuthorizationSection = CType(config.GetSection("system.web/authorization"), AuthorizationSection)

Dim rule As New AuthorizationRule(AuthorizationRuleAction.Allow)
rule.Roles.Add("admins")
section.Rules.Add(rule)

config.Save()

ASP.NET needs web.config write permission for this to work, so be careful.

Corbin March