基于角色的代码权限

基于角色的代码权限

演示了.NET中基于角色的安全控制,并且演示了安全控制中,对应用程序域的初始化步骤。

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

public class WindowsForm : System.Windows.Forms.Form
{
    
public static void Main()
    
{
        AppDomain currentDomain 
= AppDomain.CurrentDomain;
        currentDomain.SetPrincipalPolicy(
            System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
        Application.Run(
new WindowsForm());
    }


    
private Button btnOp1, btnOp2;
    
    
public WindowsForm()
    
{
        btnOp1 
= new Button();
        btnOp1.Text 
= "操作A(本操作对角色无要求)";
        btnOp1.Size 
= new Size(30023);
        btnOp1.Location 
= new Point(1020);
        btnOp1.Click 
+= new EventHandler(OnOperation1);
        
this.Controls.Add(btnOp1);
        
        btnOp2 
= new Button();
        btnOp2.Text 
= "操作B(本操作要求本机管理员权限)";
        btnOp2.Size 
= new Size(30023);
        btnOp2.Location 
= new Point(1060);
        btnOp2.Click 
+= new EventHandler(OnOperation2);
        
this.Controls.Add(btnOp2);
        
        
this.Size = new Size(360180);
    }

    
    
private void OnOperation1(object sender, EventArgs e)
    
{
        MessageBox.Show(
"操作A");
    }
    
    
    [System.Security.Permissions.PrincipalPermission(
        System.Security.Permissions.SecurityAction.Demand,
        Role
="Administrators")]
    
private void OnOperation2(object sender, EventArgs e)
    
{
        MessageBox.Show(
"操作B");
    }
    
}

原文地址:https://www.cnblogs.com/hcfalan/p/504816.html