В чем разница между получением WindowsPrincipal от WindowsIdentity и Thread.currentPrincipal?
-
14-10-2019 - |
Вопрос
Я пытаюсь понять, почему безопасность на основе атрибутов не работает, как я ожидал в WCF, и я подозреваю, что это может быть связано с следующим:
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
var identity = new WindowsIdentity("ksarfo");
var principal = new WindowsPrincipal(identity);
Console.WriteLine("\nChecking whether current user [" + identity.Name + "] is member of [" + groupName + "]");
Console.WriteLine(principal.IsInRole(groupName)); // returns true
principal = (WindowsPrincipal)Thread.CurrentPrincipal;
identity = (WindowsIdentity) principal.Identity;
Console.WriteLine("\nChecking whether current user [" + identity.Name + "] is member of [" + groupName + "]");
Console.WriteLine(principal.IsInRole(groupName)); // returns false
Я не понимаю, почему результаты различаются для вызова функции:
principal.IsInRole(groupName)
Для полноты, в которой код фактически не сбоится здесь:
PrincipalPermission(SecurityAction.Demand, Role = "PortfolioManager")]
Помогите оценить.
Решение
Может быть, это потому, что это не те же классы.
Посмотрите на MSDN:
Итак, если есть разные классы, возможно, есть различные реализации.
РЕДАКТИРОВАТЬ :
Я попробовал этот код:
public class InGroup
{
public string Name { get; set; }
public bool Current { get; set; }
public bool Fixe { get; set; }
public bool Thread { get; set; }
}
WindowsIdentity current = System.Security.Principal.WindowsIdentity.GetCurrent();
WindowsPrincipal principalcurrent = new WindowsPrincipal(current);
WindowsIdentity fixe = new WindowsIdentity("JW2031");
WindowsPrincipal principalFixe = new WindowsPrincipal(fixe);
IPrincipal principalThread = System.Threading.Thread.CurrentPrincipal;
List<InGroup> ingroups = new List<InGroup>();
foreach (IdentityReference item in current.Groups)
{
IdentityReference reference = item.Translate(typeof(NTAccount));
Console.WriteLine("{0}\t{1}\t{2}\t{3}",
reference.Value,
principalcurrent.IsInRole(reference.Value),
principalFixe.IsInRole(reference.Value),
principalThread.IsInRole(reference.Value));
ingroups.Add(new InGroup()
{
Name = reference.Value,
Current = principalcurrent.IsInRole(reference.Value),
Fixe = principalFixe.IsInRole(reference.Value),
Thread = principalThread.IsInRole(reference.Value)
});
}
foreach (IdentityReference item in fixe.Groups)
{
IdentityReference reference = item.Translate(typeof(NTAccount));
if (ingroups.FindIndex(g => g.Name == reference.Value) == -1)
{
ingroups.Add(new InGroup()
{
Name = reference.Value,
Current = principalcurrent.IsInRole(reference.Value),
Fixe = principalFixe.IsInRole(reference.Value),
Thread = principalThread.IsInRole(reference.Value)
});
Console.WriteLine("{0}\t{1}\t{2}\t{3}",
reference.Value,
principalcurrent.IsInRole(reference.Value),
principalFixe.IsInRole(reference.Value),
principalThread.IsInRole(reference.Value));
}
}
И вот есть результат
Как видите, у меня не было одинаковых групп с разными способами. Поэтому (потому что я администратор моей локальной машины), я думаю, что WindowsIdentity.getCurrent получит пользователя из Ad и WindowsPrincipal (WindowsIdentity ("" ")) доставит пользователя из локальной машины.
В моем веб -приложении у меня есть самое низкое разрешение (я думаю). Но у меня нет объяснений для Consoleapp ...
Это только предположения, но это последовательно.
Другие советы
Я полагаю, что разница заключается в том, чтобы между регистрацией в пользователе и учетной записью, запущенной приложением (поток). Это не всегда будет одинаковым.
Я признаю, что это довольно уродливый обходной путь, но если все остальное не удалось, вы можете заменить:
principal = (WindowsPrincipal)Thread.CurrentPrincipal;
с чем -то вроде
principal = new WindowsPrincipal(new WindowsIdentity(Thread.CurrentPrincipal.Identity.Name));
Если это не сработает, это, вероятно, по крайней мере будет поучительным, показывая, где дела идут не так.
Но я не могу себе представить, что это не удалось, так как это делает то же самое (где это актуально), как работа, которая работала: я предполагаю Thread.CurrentPrincipal.Identity.Name
является "ksarfo"
.