本文整理汇总了C#中System.DirectoryServices.AccountManagement.PrincipalContext类的典型用法代码示例。如果您正苦于以下问题:C# PrincipalContext类的具体用法?C# PrincipalContext怎么用?C# PrincipalContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
PrincipalContext类属于System.DirectoryServices.AccountManagement命名空间,在下文中一共展示了PrincipalContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UserInGroup
public static bool UserInGroup(IPrincipal user, params AdGroup[] groups)
{
using (WindowsImpersonationContextFacade impersonationContext
= new WindowsImpersonationContextFacade(
nc))
{
var context = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName,
user.Identity.Name);
if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(AdGroup.SuperAdmin)))
{
return true;
} //Если юзер Суперадмин
if (userPrincipal.IsMemberOf(context, IdentityType.Sid,
AdUserGroup.GetSidByAdGroup(AdGroup.SpeCalcKontroler)))
{
return true;
} //Если юзер Контролер
foreach (var grp in groups)
{
if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp)))
{
return true;
}
}
return false;
}
}
示例2: treeViewGroup_AfterSelect
private void treeViewGroup_AfterSelect(object sender, TreeViewEventArgs e)
{
try
{
//Start of: Change Font of selected node
if (prevNode != null)
{
prevNode.ForeColor = Color.Black;
prevNode.NodeFont = new Font(Font.FontFamily, Font.Size, FontStyle.Regular);
}
prevNode = treeViewGroup.SelectedNode;
treeViewGroup.SelectedNode.ForeColor = Color.Blue;
treeViewGroup.SelectedNode.NodeFont = new Font(Font.FontFamily.Name, Font.Size, FontStyle.Regular);
//End of: Change Font of selected node
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, treeViewGroup.SelectedNode.ImageKey);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, treeViewGroup.SelectedNode.Text);
userDetails = (from u in grp.Members
select new UserDetails { DisplayName = u.DisplayName, UserName = u.SamAccountName,Domain = u.Context.Name }).OrderBy(x => x.DisplayName).ToList();
userControlListing.DataSource = userDetails;
}
catch (Exception)
{
throw;
}
}
示例3: AuthorizeCore
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (base.AuthorizeCore(httpContext))
{
/* Return true immediately if the authorization is not
locked down to any particular AD group */
if (String.IsNullOrEmpty(Groups))
{
return true;
}
string DomainName = ConfigurationManager.AppSettings["Domain"].ToString();
if (string.IsNullOrEmpty(DomainName))
{
throw new ArgumentException("Domain missing from AppSettings!");
}
// Get the AD groups
var groups = Groups.Split(',').ToList();
// Verify that the user is in the given AD group (if any)
var context = new PrincipalContext(ContextType.Domain,DomainName);
var userPrincipal = UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,httpContext.User.Identity.Name);
foreach (var group in groups)
{
if (userPrincipal.IsMemberOf(context, IdentityType.Name, group))
{
return true;
}
}
}
return false;
}
示例4: button1_Click
private void button1_Click(object sender, EventArgs e)
{
if (this.txtUserName.Text.Length < 1)
{
MessageBox.Show("Please Enter User Name");
return;
}
if (this.txtPassword.Text.Length < 1)
{
MessageBox.Show("Please Enter Password");
return;
}
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "COS");
principalContext.ValidateCredentials(this.txtUserName.Text, this.txtPassword.Text);
try
{
if (!principalContext.ValidateCredentials(this.txtUserName.Text, this.txtPassword.Text))
{
this.txtPassword.Text = string.Empty;
MessageBox.Show("User Name or Password Not correct");
}
else
{
(new frmMain()).Show();
base.Hide();
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
示例5: _LoggedInAs
public ActionResult _LoggedInAs()
{
User user = new User();
try
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal) Thread.CurrentPrincipal;
//String adDomainUserName = principal.Identity.Name;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
user.FirstName = up.GivenName;
user.LastName = up.Surname;
user.Email = up.EmailAddress;
user.UserName = (principal.Identity.Name).Split('\\')[1];
}
/* if (adDomainUserName != null)
{
string adUserName = adDomainUserName.Split('\\')[1];
user = _ldapService.GetUserByUserName(adUserName);
}*/
}
catch (Exception e)
{
logger.Error("Exception", e);
}
Session["user"] = user;
return View(user);
}
示例6: Create
public ActionResult Create()
{
var name = User.Identity.Name;
UserPrincipal user;
using (var pc = new PrincipalContext(ContextType.Domain, "smausa"))
{
user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, name);
}
if (user == null)
{
throw new Exception("Active Directory user not found!");
}
var player = new Player
{
Username = name,
FirstName = user.GivenName,
Surname = user.Surname,
Email = user.EmailAddress,
Notifications = !string.IsNullOrWhiteSpace(user.EmailAddress)
};
return View(player);
}
示例7: IsGroupMember
private static bool IsGroupMember(string userName, string Group)
{
#if DEBUG
return true;
//PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com", "fmedvedik", "(manos)3k");
//PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "10.0.0.2", "fmedvedik", "(manos)3k");
// PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
#else
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com");
var findByIdentity = UserPrincipal.FindByIdentity(ctx, userName);
bool retVal = false;
if (findByIdentity != null)
{
List<string> result;
using (var src = findByIdentity.GetGroups(ctx))
{
result = new List<string>();
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
}
var l = result.FirstOrDefault(s => s.Equals(Group));
retVal = (l != null);
}
ctx.Dispose();
return retVal;
#endif
}
示例8: FindByIdentity
// Implement the overloaded search method FindByIdentity.
public static new ExtendedUserPrincipal FindByIdentity(PrincipalContext context,
string identityValue)
{
return (ExtendedUserPrincipal)FindByIdentityWithType(context,
typeof(ExtendedUserPrincipal),
identityValue);
}
示例9: Login
public bool Login(String userName, String password)
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, this.domainName);
bool isValid = false;
isValid = pc.ValidateCredentials(userName, password);
return isValid;
}
示例10: getMatchingStudents
public static List<Student> getMatchingStudents(string givenName, string surname)
{
List<Student> matches = new List<Student>();
using (PrincipalContext pc = new PrincipalContext(
ContextType.ApplicationDirectory, "ailds01v.home.ad1.sou.edu:1556",
"CN=Users,CN=University", ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
{
SouPerson findPerson = new SouPerson(pc);
findPerson.GivenName = givenName;
findPerson.Surname = surname;
PrincipalSearcher searcher = new PrincipalSearcher(findPerson);
PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (SouPerson person in results)
{
if (person.souStudent == true)
{
Student s = new Student();
s.setKey1(person.souStudentKey1);
s.setKey2(person.souStudentKey2);
s.setUsername(person.Name);
matches.Add(s);
}
}
return matches;
}
}
示例11: GetClientRoles
internal static IEnumerable<BplRole> GetClientRoles(string loginName) {
try {
using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) {
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) {
try {
var groups = user.GetAuthorizationGroups();
var roles = groups.Select(g => BplRole.Get(g.Name)).Where(r => r != null).ToArray();
return roles;
} catch (PrincipalOperationException pex) {
Log.Exception(pex, Severity.Warning, "Unable to retrive client roles on trusted domain. Fall back to untrusted.");
}
//TK: Fallback to untrusted communication or DNS issues. I do not believe i need to do this!
var usr = (DirectoryEntry)user.GetUnderlyingObject();
var dgroups = usr.Invoke("Groups");
var droles = new List<BplRole>();
foreach (var g in (IEnumerable)dgroups) {
var ge = new DirectoryEntry(g);
var role = BplRole.Get(ge.Name.RemoveAll("CN="));
if (role != null) {
droles.Add(role);
}
}
return droles;
}
}
} catch (Exception e) {
Log.Exception(e, "Unable to retrive client roles");
}
return null;
}
示例12: IsUserMemberOfAccessControlGroup
public bool IsUserMemberOfAccessControlGroup(string accessControlGroup)
{
if (string.IsNullOrWhiteSpace(accessControlGroup))
{
return true;
}
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
GroupPrincipal groupPrincipal = GroupPrincipal
.FindByIdentity(principalContext, accessControlGroup);
if (groupPrincipal == null)
{
throw new FingertipsException("Could not find group: " + accessControlGroup);
}
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Name);
if (userPrincipal == null)
{
throw new FingertipsException("Could not find user: " + Name);
}
return userPrincipal.IsMemberOf(groupPrincipal);
}
示例13: crearEstudiante2
//BASARSE EN ESTO PARA ARREGLAR TODO LO QUE SEA CON EL AD
//Una mejor manera de hacerlo http://johnbarquin.wordpress.com/2008/06/12/servicios-de-directorio-en-net-35/
/// <summary>
/// Método que se encarga de crear un usuario estudiante en Active Directory
/// </summary>
/// <param name="estudiante">
/// Los datos del estudiante (en un tipo Usuario) por ingresar a Active Directory
/// </param>
public Boolean crearEstudiante2(Usuario estudiante)
{
String nombre_completo = estudiante.Carnet + " " + estudiante.Nombre + " " + estudiante.Apellidos + " " + estudiante.Carrera;
try {
PrincipalContext contextoDominio = new PrincipalContext(ContextType.Domain, Constantes.DOM, Constantes.AD_USER, Constantes.AD_PASS);
UserPrincipal usuario = new UserPrincipal(contextoDominio, estudiante.UID, estudiante.Contrasena, true);
usuario.SamAccountName = estudiante.UID;// LEGACY: Cuenta de estudiante Pre-Win2000
usuario.UserPrincipalName = estudiante.UID + Constantes.DOMINIO;//Debe de contener el dominio
usuario.GivenName = estudiante.Nombre;
usuario.Surname = estudiante.Apellidos;
usuario.DisplayName = nombre_completo;
usuario.Description = "Estudiante";
usuario.HomeDirectory = getHomeDirectoryAD(estudiante);
usuario.EmailAddress = estudiante.Correo;
usuario.HomeDrive = "M";
usuario.PasswordNeverExpires = true;
usuario.Save();
usuario.SetPassword(estudiante.Contrasena);
usuario.Save();
return true;
}
catch (Exception e)
{
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "");
return false;
}
}
示例14: buttonGetUsers_Click
private void buttonGetUsers_Click(object sender, EventArgs e)
{
_users = loadUsersFromTxt();
if (_users.Count == 0)
{
string domainName = textBoxDomain.Text;
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, textBoxGroup.Text);
if (group != null)
{
HashSet<UserData> usersHash = new HashSet<UserData>();
IterateGroup(group, usersHash);
_users = usersHash.ToList();
}
else
{
MessageBox.Show("Группа не найдена");
}
}
}
listBoxUsers.DataSource = _users.ToList();
saveUsersToTxt(_users);
MessageBox.Show("Готово");
}
示例15: SearchComp
private static void SearchComp(List<CompData> comps, string domainName)
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))
{
foreach (var comp in comps)
{
if (comp.CompName == null)
{
var sp = new ComputerPrincipal(ctx);
sp.Description = comp.User.Name;
var searcher = new PrincipalSearcher(sp);
var res = searcher.FindAll();
foreach (var p in res)
{
if (p is ComputerPrincipal)
{
var findComp = (ComputerPrincipal)p;
comp.CompName = findComp.Name;
comp.CompPath = findComp.DistinguishedName;
}
}
}
}
}
}