手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网络编程>Asp.Net编程>列表

学习一下.net framework 中有关安全的内容

来源:互联网 作者:west263.com 时间:2008-02-22
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

  好容易在繁重的开发任务之余抽出点时间学习一些东西。发现机子里有几个关于 System.Security 内容的示例,这一个命名空间以前还真是从来没用过,正好拿来学习一下。由于不是系统的学习,不好组织,想了想,就以示例来说明吧。 

  一、设定权限

1[FileIOPermission(SecurityAction.Demand, Write= "C:\\temp.txt")]
2public class App : System.Windows.Forms.Form
3{
4 //略
5}
  FileIOPermissionAttribute 定义于 System.Security.Permissions 里。它继承于 SecurityAttribute,在这个例子中,要求使用 App 类时必须具有对 C:\temp.txt 文件的写权限。

  .net framework 的文档中关于安全要求有这样一段话:“若要确保只有被授予了指定权限的调用方才能够调用您的代码,可以声明方式或强制方式要求您的代码的调用方拥有特定的权限或权限集。要求使运行库执行安全检查,从而对调用代码实施限制。在安全检查过程中,运行库遍历调用堆栈,检查堆栈中每个调用方的权限,然后确定是否已将要求的权限授予每个调用方。如果发现某个调用方没有要求的权限,则安全检查失败,并引发 SecurityException。”

  例子中,权限是以声明的方式出现的。SecurityAction.Demand 可以作用于类或方法,在这里是作用于类上。Write 是 FileIOPermission 的属性之一,其它常用属性还有 Read、Append、All 等等。

  SecurityAction 枚举中还有一些值是作用于 assembly 上的。比如以下的例子:

[assembly:SecurityPermission(SecurityAction.RequestMinimum ,UnmanagedCode=true)]
  SecurityAction.RequestMinimum 是请求运行的最小权限。这一行要求程序集允许调用非托管代码。

  除了声明方式外,还可以使用强制方式。如下的代码:

1FileIOPermission filePerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, "C:\\temp.txt");
2try
3{
4 filePerm.Demand();
5
6 // Code to access file goes here
7}
8catch (SecurityException excep)
9{
10 MessageBox.Show (excep.Message);
11 return;
12}
13
  二、用户角色管理

  用户及其角色的管理是在许多程序中都要使用到的。如今 asp.net 2.0 对于这方面有了大大增强,开发人员不需要很了解技术就可以做出很不错的应用。不过对于 Windows Form 应用程序来说,不少地方还需要程序员自己设定。

  假定我们已知晓了 userName 以及它所属于的 roles,那么可以这样来设置当前线程的 Principal:

1GenericIdentity genIdent = new GenericIdentity(userName);
2GenericPrincipal genPrin = new GenericPrincipal(genIdent, roles);
3Thread.CurrentPrincipal = genPrin;
4
  随后我们有三种办法来进行用户角色验证。

  第一种方法是使用 GenericPrincipal.IsInRole 方法:

1GenericPrincipal currentPrin = Thread.CurrentPrincipal as GenericPrincipal;
2
3if (currentPrin != null && currentPrin.IsInRole("Manager"))
4{
5 //略
6}
7
  第二种方法则是使用 PrincipalPermission 类,类似于权限设定中的强制方式:

1PrincipalPermission prinPerm = new PrincipalPermission(null, "Manager");
2
3try
4{
5 prinPerm.Demand();
6
7 //do something
8}
9catch
10{
11 //error handling
12}
  第三种方式则类似于权限设定中的声明方式:

1private void DecPermButton_Click(object sender, System.EventArgs e)
2{
3 try
4 {
5 performManagerAction();
6 // do something
7 }
8 catch
9 {
10 // error handling
11 }
12}
13
14[PrincipalPermission(SecurityAction.Demand, Role="Manager")]
15void performManagerAction()
16{
17}
  关于安全的另一个重要内容是加密。今天没空写了,改天再说。

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!