3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
您應(yīng)該做的是計(jì)算運(yùn)行代碼的用戶標(biāo)識(shí)的有效權(quán)限。例如,以上示例中沒(méi)有一個(gè)正確地考慮了組成員身份。
我很確定Keith Brown在他的Windows安全Windows開(kāi)發(fā)人員指南的維基版本(此時(shí)是離線版)中有一些代碼可以執(zhí)行此操作。在他的Programming Windows Security書(shū)籍中也對(duì)此進(jìn)行了詳細(xì)討論。
計(jì)算有效權(quán)限不適合膽小的人,而您的代碼嘗試創(chuàng)建文件并捕獲拋出的安全異??赡苁亲枇ψ钚〉穆窂?。

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
Deny
優(yōu)先于Allow
。本地規(guī)則優(yōu)先于繼承的規(guī)則。我已經(jīng)看到了很多解決方案(包括這里顯示的一些答案),但它們都沒(méi)有考慮規(guī)則是否是繼承的。因此,我建議采用以下方法來(lái)考慮規(guī)則繼承(整齊地包裝到類中):
public class CurrentUserSecurity{ WindowsIdentity _currentUser; WindowsPrincipal _currentPrincipal; public CurrentUserSecurity() { _currentUser = WindowsIdentity.GetCurrent(); _currentPrincipal = new WindowsPrincipal(_currentUser); } public bool HasAccess(DirectoryInfo directory, FileSystemRights right) { // Get the collection of authorization rules that apply to the directory. AuthorizationRuleCollection acl = directory.GetAccessControl() .GetAccessRules(true, true, typeof(SecurityIdentifier)); return HasFileOrDirectoryAccess(right, acl); } public bool HasAccess(FileInfo file, FileSystemRights right) { // Get the collection of authorization rules that apply to the file. AuthorizationRuleCollection acl = file.GetAccessControl() .GetAccessRules(true, true, typeof(SecurityIdentifier)); return HasFileOrDirectoryAccess(right, acl); } private bool HasFileOrDirectoryAccess(FileSystemRights right, AuthorizationRuleCollection acl) { bool allow = false; bool inheritedAllow = false; bool inheritedDeny = false; for (int i = 0; i < acl.Count; i++) { var currentRule = (FileSystemAccessRule)acl[i]; // If the current rule applies to the current user. if (_currentUser.User.Equals(currentRule.IdentityReference) || _currentPrincipal.IsInRole( (SecurityIdentifier)currentRule.IdentityReference)) { if (currentRule.AccessControlType.Equals(AccessControlType.Deny)) { if ((currentRule.FileSystemRights & right) == right) { if (currentRule.IsInherited) { inheritedDeny = true; } else { // Non inherited "deny" takes overall precedence. return false; } } } else if (currentRule.AccessControlType .Equals(AccessControlType.Allow)) { if ((currentRule.FileSystemRights & right) == right) { if (currentRule.IsInherited) { inheritedAllow = true; } else { allow = true; } } } } } if (allow) { // Non inherited "allow" takes precedence over inherited rules. return true; } return inheritedAllow && !inheritedDeny; }}
但是,我的經(jīng)驗(yàn)是,這并不總是適用于遠(yuǎn)程計(jì)算機(jī),因?yàn)槟鸁o(wú)法始終查詢那里的文件訪問(wèn)權(quán)限。在這種情況下的解決方案是嘗試; 甚至可能只是嘗試創(chuàng)建一個(gè)臨時(shí)文件,如果您需要在使用“真實(shí)”文件之前知道訪問(wèn)權(quán)限。
- 3 回答
- 0 關(guān)注
- 563 瀏覽
添加回答
舉報(bào)