随着ADO.NET的发展,我们运用起来也非常紧张,这里就使用ADO.NET CAS权限验证代码。这里我们就详细的分析一下吧。对于部分信任方案,可以通过指定SqlClientPermissionAttribute来要求代码中的特定方法具有CAS特权。如果当前受限制的安全策略不允许该权限,在运行代码之前将引发异常。有关安全策略的更多信息,请参见安全策略管理和安全策略最佳实施策略。
#T#在设计ADO.NET CAS权限时,正确的模式是以限制性最强的情况开始(无任何权限),然后添加代码执行特定任务所需的特定权限。相反的模式是一开始就授予所有权限,然后拒绝特定权限,这样做是不安全的,因为表达同一连接字符串可以有许多方式。例如,如果一开始就授予所有权限,然后尝试拒绝使用连接字符串“server=someserver”,则仍将允许使用“server=someserver.mycompany.com”。通过在开始时始终不授予任何权限,可以降低权限集中存在漏洞的几率。
下面的代码演示SqlClient如何执行安全请求,如果没有相应的ADO.NET CAS权限,将引发SecurityException。控制台窗口中显示SecurityException输出。
- PrivateSubTestCAS(ByValconnectString1AsString,ByValconnectString2AsString)
- 'SimulateremovingSqlClientpermissions.
- DimpermissionAsNewSqlClientPermission(PermissionState.Unrestricted)
- permission.Deny()
- 'Trytoopenaconnection.
- Try
- UsingconnectionAsNewSqlConnection(connectString1)
- connection.Open()
- Console.WriteLine("Connectionopened,unexpected.")
- EndUsing
- CatchexAsSystem.Security.SecurityException
- Console.WriteLine("Failed,asexpected:{0}",_
- ex.FirstPermissionThatFailed)
- 'UncommentthefollowinglinetoseeExceptiondetails.
- 'Console.WriteLine("BaseException:{0}",ex.GetBaseException())
- EndTry
- SqlClientPermission.RevertAll()
- 'Addpermissionforaspecificconnectionstring.
- 'Thiswouldtypicallybeachievedbytheadministrator
- 'deployingaCASpolicy,notinyourcode.
- permission=NewSqlClientPermission(PermissionState.None)
- permission.Add(connectString1,"",KeyRestrictionBehavior.AllowOnly)
- permission.PermitOnly()
- 'Tryagain,itshouldsucceednow.
- Try
- UsingconnectionAsNewSqlConnection(connectString1)
- connection.Open()
- Console.WriteLine("Connectionopened,asexpected.")
- EndUsing
- CatchexAsSystem.Security.SecurityException
- Console.WriteLine("Unexpectedfailure:{0}",ex.Message)
- EndTry
- 'Tryadifferentconnectionstring.Thisshouldfail.
- Try
- UsingconnectionAsNewSqlConnection(connectString2)
- connection.Open()
- Console.WriteLine("Connectionopened,unexpected.")
- EndUsing
- CatchexAsSystem.Security.SecurityException
- Console.WriteLine("Failed,asexpected:{0}",ex.Message)
- EndTry
- EndSub
在控制台窗口中应看到以下输出:
- Failed,asexpected:<IPermissionclassIPermissionclass="System.Data.SqlClient.
- SqlClientPermission,System.Data,Version=2.0.0.0,
- Culture=neutral,PublicKeyToken=b77a5c561934e089"version="1"
- AllowBlankPassword="False">
- <addConnectionStringaddConnectionString="DataSource=(local);InitialCatalog=
- Northwind;IntegratedSecurity=SSPI"KeyRestrictions=""
- KeyRestrictionBehavior="AllowOnly"/>
- </IPermission>
- Connectionopened,asexpected.
- Failed,asexpected:Requestfailed.