我真的很困惑,应该将User
属性传递给PrincipalPermission
装饰器。我刚刚在.NET 4.6.1中创建了全新的WPF应用程序(但我也尝试过4.5.2和4.0),我只用了一个单击事件按钮:
[PrincipalPermission(SecurityAction.Demand, Name = "MYDOMAIN\\myusername")]
private void foo_Click(object sender, RoutedEventArgs e)
{
var user = WindowsIdentity.GetCurrent().Name; // this returns: MYDOMAIN\\myusername
}
我正在申请校长许可失败。为什么?
我也尝试过:
[PrincipalPermission(SecurityAction.Demand, Name = "myusername")]
[PrincipalPermission(SecurityAction.Demand, Name = "sysadmin")]
[PrincipalPermission(SecurityAction.Demand, Role = "DEVELOPERS")]
[PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
我甚至尝试过:
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
它只是不起作用..我做错了什么?如果重要,我有VS2015。
修改
让我进一步简化:
偶然点击一个按钮:
private void foo_Click(object sender, RoutedEventArgs e)
{
Test();
}
public bool Test()
{
try
{
var userName = WindowsIdentity.GetCurrent().Name;
var group = GetGroups(userName).FirstOrDefault();
var p = new PrincipalPermission(userName, group);
p.Demand();
}
catch (SecurityException)
{
throw;
}
return true;
}
private static String[] GetGroups(string userName)
{
var toReturn = new List<String>();
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(ctx, userName))
{
if (user != null)
{
var output = user.GetGroups().Select(x => x.SamAccountName).ToArray();
foreach (var group in output)
toReturn.Add(group);
}
}
return toReturn.ToArray();
}
Whyyy?
答案 0 :(得分:0)
据我所知,如果您想将方法限制为名为GroupA
的组,您可以使用
[PrincipalPermission(SecurityAction.Demand, Role = "GroupA")]
请注意使用PrincipalPermission.Role
代替PrincipalPermission.Name
。您有一个名为username
的组吗?我想不是,这可能是问题所在。我不确定您是否可以将方法限制为单个用户名,我只知道限制用户组。
我知道PrincipalPermission.Name
的唯一用法是你是否使用证书,例如
[PrincipalPermission(SecurityAction.Demand, Name = "CN=<SubjectName>; <Certificate Thumbprint>")]