預設情況下,自訂組合語言程式碼會以有限的 執行 權限設定執行。 在某些情況下,你可能想實作一個自訂的組裝,對安全系統中的受保護資源(例如檔案或登錄檔)進行安全呼叫。 為達成此目標,您必須採取以下步驟:
確定你的程式碼需要的精確權限,才能進行安全通話。 若此方法屬於 Microsoft .NET Framework 函式庫,則此資訊應包含在方法文件中。
修改報告伺服器的政策設定檔,以賦予自訂組合所需的權限。 欲了解更多安全政策設定檔的資訊,請參閱使用 Reporting Services 安全政策檔案。
在進行安全通話時,請先聲明必要的權限。 這是必要的,因為報告伺服器呼叫的自訂組合語言是報告表達式 host assembly 的一部分, 預設執行權限 為執行權限。 執行權限集允許程式碼執行,但無法使用受保護的資源。
如果自訂組件有強名稱,請用 AllowPartiallyTrustedCallersAttribute 標記。 這是必要的,因為自訂組件是從報告表達式 host assembly 中的報告表達式呼叫,而該表達式預設不被賦予 FullTrust;因此它是一個「部分可信」的來電者。 更多資訊請參閱 使用 Strong-Named 自訂組件。
實作安全通話
你可以修改政策設定檔,賦予你的組合特定權限。 舉例來說,如果你在撰寫一個自訂組件來處理貨幣轉換,你可能需要從檔案讀取當前的匯率。 要取得速率資訊,你需要在組裝權限集中新增一個額外的安全權限 FileIOPermission。 你可以在政策設定檔中額外輸入以下內容:
<PermissionSet class="NamedPermissionSet"
version="1"
Name="CurrencyRatesFilePermissionSet"
Description="A special permission set that grants read access to my currency rates file.">
<IPermission class="FileIOPermission"
version="1"
Read="C:\CurrencyRates.xml"/>
<IPermission class="SecurityPermission"
version="1"
Flags="Execution, Assertion"/>
</PermissionSet>
接著你加入一個代碼群組,參考該權限集:
<CodeGroup class="UnionCodeGroup"
version="1"
PermissionSetName="CurrencyRatesFilePermissionSet"
Name="MyNewCodeGroup"
Description="A special code group for my custom assembly.">
<IMembershipCondition class="UrlMembershipCondition"
version="1"
Url="C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\MSSQL\Reporting Services\ReportServer\bin\CurrencyConversion.dll"/>
</CodeGroup>
為了讓你的程式碼獲得適當的權限,你必須在自訂組合程式碼中主張該權限。 例如,如果你想對一個 XML 檔案 C:\CurrencyRates.xml添加唯讀存取,你必須在方法中加入以下程式碼:
// C#
FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, @"C:\CurrencyRates.xml");
try
{
permission.Assert();
// Load the XML currency rates file
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\CurrencyRates.xml");
...
你也可以將斷言作為方法屬性加入:
[FileIOPermissionAttribute(SecurityAction.Assert, Read=@"C:\CurrencyRates.xml")]
欲了解更多資訊,請參閱 .NET 框架開發者指南中的「.NET 框架安全性」。