為了避免使用者取得他們不應該存取的資料,

.NET FRAMEWORK提供了安全性的物件, 限制使用者的存取權限.
這跟Windows本身的帳戶安全性有些不同, 是針對程式而言.

SecurityAction 屬性有三種:

  • RequestMinimum(M) 正常執行的最小權限
  • RequestOptional(O) 可有可無的權限
  • RequestRefuse(R) 絕對不能有的權限

*P = Security Policy (也就是Enterprise, Machine, User三者的交集)

最終權限的決定放程式為:  (P 交 ((M 聯 O) – R))

以下範例顯示:只允許使用者存取特定的資料表, 如果不是指定的資料表, 就無法執行程式:

注: RequestOptional, Unrestricted應設為False, 才表示不允許給予其他的權限; 如果設為True, 則表示沒有限制, 所有權限的給了(很危險, 容易造成駭客的入侵).

Imports System.Security.Permissions
Imports System.Data.SqlClient

<Assembly: UIPermission(SecurityAction.RequestMinimum, Window:=UIPermissionWindow.SafeTopLevelWindows)>
<Assembly: SqlClientPermission(SecurityAction.RequestMinimum, _
         ConnectionString:="server=.;database=pubs;integrated security=true")>

<Assembly: SecurityPermission(SecurityAction.RequestOptional, Unrestricted:=False)>

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cn As New SqlConnection(TextBox1.Text)
        Try
            cn.Open()
            MessageBox.Show("連線成功")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

End Class

方法的權限安全種類:

有六種SecurityAction 可用再宣告式或命令式安全性

  • Assert
  • Demand
  • InheritanceDemand
  • LinkDemand
  • PermitOnly
  • Deny

Imports System.Security.Permissions
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    <FileIOPermission(SecurityAction.Demand)> _
    Sub CreateFile()
        Try
            File.CreateText("C:\test\b.txt")
            MessageBox.Show("b.txt has been created")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    ‘DENY表示不允許使用這個METHOD
    <FileIOPermission(SecurityAction.Deny, Write:="C:\test")> _
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        CreateFile()
    End Sub

    ‘SecurityAction.Demand的另一種寫法
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim fp As New FileIOPermission(FileIOPermissionAccess.Write, "C:\test")
        fp.Demand()
        CreateFile()
    End Sub
End Class

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>