Editing Web.config to authorize the membership role

I want role-based user protection through the authorization section in the web.config file.

Using membership, my application will allow you to create new roles, and therefore the pages that they can receive must be installed dynamically.

Can I programmatically change this section in the web.config file to manage this? If so, how?

+3
source share
1 answer
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();
 
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 requires write permission to web.config for this, so be careful.

+5
source

Source: https://habr.com/ru/post/1699170/


All Articles