简体   繁体   中英

C# How to get the AD user cannot change the password property from LDAP attribute userAccountControl?

I am trying to get the user account control properties using library Novell.Directory.Ldap in ASP .NET Core 5 . When I search the users attributes I found the attribute name userAccountControl which is set to some number. After searching solution I am able to find:

bool isUserActive = false;
bool userMustChangePassword = false;
bool passwordNeverExpires = false;
bool passwordCannotBeChanged = false;

var flags = Convert.ToInt32(attributeSet.GetAttribute("userAccountControl").StringValue);
isUserActive = !Convert.ToBoolean(flags & 0x0002); //1. checks if user is enabled
if ((flags == 66048)) //65536+512
{
  passwordNeverExpires = true; //2. Password never expires property
}
long value = Convert.ToInt64(attributeSet.GetAttribute("pwdLastSet").StringValue);
if (value == 0)
{
    userMustChangePassword = true; //3. User must change password at next login
}

But I am not able to figure out how to get the User cannot change password and if the account is locked properties? Or how can I compare the binary value like 0x0040 ? Please help

The userAccountControl value is a bit flag, meaning that every bit in the binary representation of the number is an "on" or "off" depending on if it's a 1 or 0. So the decimal value is meaningless.

You are already checking the value properly when you're checking if it's enabled:

isUserActive = !Convert.ToBoolean(flags & 0x0002); //1. checks if user is enabled

Likewise, you should do the same when checking any of the other flags. The value of each is listed in the documentation .

When you're checking if the password is set to never expire, you're comparing the decimal value, which won't always give you a correct answer. Instead, check the bit value:

passwordNeverExpires = Convert.ToBoolean(flags & 0x10000);

Similar for if the user cannot change the password:

var userCannotChangePassword = Convert.ToBoolean(flags & 0x0040);

And account is locked:

var accountLocked = Convert.ToBoolean(flags & 0x0010);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM