本文整理汇总了C#中System.Security.Principal.NTAccount类的典型用法代码示例。如果您正苦于以下问题:C# NTAccount类的具体用法?C# NTAccount怎么用?C# NTAccount使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
NTAccount类属于System.Security.Principal命名空间,在下文中一共展示了NTAccount类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DeleteUserProfile
/// <summary>
/// Deletes the user profile.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="domainName">The domain name of the user to act as.</param>
public static void DeleteUserProfile(string userName, string domainName)
{
NTAccount ntaccount = new NTAccount(domainName, userName);
string userSid = ntaccount.Translate(typeof(SecurityIdentifier)).Value;
bool retry = true;
int retries = 2;
while (retry && retries > 0)
{
retry = false;
if (!DeleteProfile(userSid, null, null))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == 2)
{
// Error Code 2: The user profile was not created or was already deleted
return;
}
else if (errorCode == 87)
{
// Error Code 87: The user profile is still loaded.
retry = true;
retries--;
}
else
{
throw new Win32Exception(errorCode);
}
}
}
}
示例2: CreateSddl
private static string CreateSddl(string account)
{
string sid = new NTAccount(account).Translate(typeof(SecurityIdentifier)).ToString();
// DACL that Allows Generic eXecute for the user specified by account
// see help for HttpServiceConfigUrlAclParam for details on what this means
return string.Format(CultureInfo.CurrentCulture, "D:(A;;GX;;;{0})", sid);
}
示例3: MainWindow
// Constructor //
public MainWindow()
{
InitializeComponent();
// Get user name
this.username = Environment.UserName.ToString();
// Get user SID
NTAccount acct = new NTAccount(username);
SecurityIdentifier s = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
this.usrSID = s.ToString();
// Get user home directory
this.homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
// Get volume location (default)
this.defaultVolumeLoc = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)) + this.username + ".hc";
// Figure out where the home folder's encrypted file is located for this user //
string encDrive = (string)Registry.GetValue(Config.LOCAL_MACHINE_REG_ROOT + this.usrSID, "encDrive", string.Empty);
string encContainerLoc = (string)Registry.GetValue(Config.LOCAL_MACHINE_REG_ROOT + this.usrSID, "encContainerLoc", string.Empty);
if (!string.IsNullOrWhiteSpace(encContainerLoc) && !string.IsNullOrWhiteSpace(encDrive) && Directory.Exists(encDrive + @":\"))
{
// We're already running in an encrypted home directory environment!
g_tabContainer.Controls[0].Enabled = false;
l_homeAlreadyEncrypted.Visible = true;
l_homeAlreadyEncrypted.Enabled = true;
}
// * //
l_statusLabel.Text = "Ready ...";
Application.DoEvents();
}
示例4: btnOK_Click
private void btnOK_Click(object sender, EventArgs e)
{
bool success = false;
try
{
Sid = new SecurityIdentifier(textBoxSid.Text);
success = true;
}
catch (Exception)
{
}
if (!success)
{
try
{
NTAccount acct = new NTAccount(textBoxSid.Text);
Sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
success = true;
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (success)
{
DialogResult = DialogResult.OK;
Close();
}
}
示例5: FindSid
public SidWrapper FindSid(string account)
{
SecurityIdentifier sid = null;
try
{
// first, let's try this as a sid (SDDL) string
sid = new SecurityIdentifier(account);
return new SidWrapper { Sid = sid};
}
catch
{
}
try
{
// maybe it's an account/group name
var name = new NTAccount(account);
sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
if (sid != null)
{
return new SidWrapper { Sid = sid };
}
}
catch
{
}
return null;
}
示例6: Execute
public void Execute()
{
PrintHeader();
var id = WindowsIdentity.GetCurrent();
Console.WriteLine("Identity Id: " + id.Name);
var account = new NTAccount(id.Name);
var sid = account.Translate(typeof(SecurityIdentifier));
Console.WriteLine("SecurityIdentifier (sid): " + sid.Value);
foreach (var group in id.Groups.Translate(typeof(NTAccount)))
Console.WriteLine("InGroup: " + group);
var principal = new WindowsPrincipal(id);
var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins));
var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins));
Console.WriteLine();
// be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights,
// unless the process was run elevated "as Admin".
}
示例7: RemoveUser
public static void RemoveUser(string targetDir, string user, string windowsUser, string userHomeDir, string userShell)
{
string passwdFile = Path.Combine(targetDir, "etc", "passwd");
string userSID = null;
try
{
var objUser = new NTAccount(windowsUser);
userSID = ((SecurityIdentifier)objUser.Translate(typeof(SecurityIdentifier))).Value;
}
catch
{
throw new Exception(string.Format("Could not get SID for user {0}. Aborting.", windowsUser));
}
string usersGroupSID = CygwinPasswd.GetNoneGroupSID();
Logger.Debug("Setting up user in passwd file...");
string uid = userSID.Split('-').Last();
string gid = usersGroupSID.Split('-').Last();
string userHomeDirLinux = LinuxFiles.Cygpath(userHomeDir);
userShell = LinuxFiles.Cygpath(userShell);
string match = string.Format("{0}:unused:{1}:{2}:{3},{4}:{5}:{6}", user, uid, gid, windowsUser, userSID, userHomeDirLinux, userShell);
List<string> content = File.ReadAllLines(passwdFile).ToList();
content.Remove(match);
File.WriteAllLines(passwdFile, content, Encoding.ASCII);
}
示例8: GetUncPathForDrive
public string GetUncPathForDrive(string domain, string user, string drive)
{
var userIdentifier = String.Format(@"{0}\{1}", domain, user);
if (!driveCache.ContainsKey(userIdentifier))
{
var account = new NTAccount(domain, user);
if (account == null)
return null;
var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
if (sid == null)
return null;
var drives = RegistryReader.GetSubKeys(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network", sid.Value));
if (drives == null)
return null;
driveCache[userIdentifier] = drives.Select(driveLetter => {
string uncPath = RegistryReader.ReadKey(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network\{1}", sid.Value, driveLetter), "RemotePath").ToString();
return new KeyValuePair<string, string>(driveLetter, uncPath);
}).Where(x => x.Value != null).ToDictionary();
}
if (driveCache[userIdentifier].ContainsKey(drive))
return driveCache[userIdentifier][drive];
return null;
}
示例9: GetSidFromClaim
public static SecurityIdentifier GetSidFromClaim(string claimValue)
{
SecurityIdentifier sid = null;
SPClaimProviderManager claimManager = SPClaimProviderManager.Local;
if (claimManager == null)
{
throw new ApplicationException("Unable to access the claims provider manager.");
}
try
{
SPClaim claim = claimManager.DecodeClaim(claimValue);
if (claim.OriginalIssuer.Equals("Windows", StringComparison.OrdinalIgnoreCase))
{
if (claim.ClaimType.Equals(Microsoft.IdentityModel.Claims.ClaimTypes.GroupSid, StringComparison.OrdinalIgnoreCase))
{
sid = new SecurityIdentifier(claim.Value);
}
else if (claim.ClaimType.Equals(Microsoft.SharePoint.Administration.Claims.SPClaimTypes.UserLogonName, StringComparison.OrdinalIgnoreCase))
{
NTAccount userAccount = new NTAccount(claim.Value);
sid = (SecurityIdentifier)userAccount.Translate(typeof(SecurityIdentifier));
}
}
}
catch (ArgumentException currentException)
{
GlymaSearchLogger.WriteTrace(LogCategoryId.Security, TraceSeverity.Unexpected, "The following exception occured when attempting to decode the claim, " + claimValue + " : " + currentException.ToString());
}
return sid;
}
示例10: ElevatePermissions
public void ElevatePermissions(string directory)
{
var account = new NTAccount(WindowsIdentity.GetCurrent().Name);
var existingDirectory = new DirectoryInfo(directory);
var existingDirectorySecurity = existingDirectory.GetAccessControl();
existingDirectorySecurity.SetOwner(account);
existingDirectory.SetAccessControl(existingDirectorySecurity);
}
示例11: AddReservation
/// <summary>
/// Adds a reservation to the list of reserved URLs
/// </summary>
/// <param name="urlPrefix">The prefix of the URL to reserve.</param>
/// <param name="user">The user with which to reserve the URL.</param>
internal static void AddReservation(string urlPrefix, string user)
{
NTAccount account = new NTAccount(user);
SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
string sddl = GenerateSddl(sid);
ErrorCode retVal = ErrorCode.Success; // NOERROR = 0
retVal = NativeMethods.HttpInitialize(HttpApiConstants.Version1, HttpApiConstants.InitializeConfig, IntPtr.Zero);
if (ErrorCode.Success == retVal)
{
HttpServiceConfigUrlAclKey keyDesc = new HttpServiceConfigUrlAclKey(urlPrefix);
HttpServiceConfigUrlAclParam paramDesc = new HttpServiceConfigUrlAclParam(sddl);
HttpServiceConfigUrlAclSet inputConfigInfoSet = new HttpServiceConfigUrlAclSet();
inputConfigInfoSet.KeyDesc = keyDesc;
inputConfigInfoSet.ParamDesc = paramDesc;
IntPtr inputConfigInfoBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HttpServiceConfigUrlAclSet)));
Marshal.StructureToPtr(inputConfigInfoSet, inputConfigInfoBuffer, false);
retVal = NativeMethods.HttpSetServiceConfiguration(
IntPtr.Zero,
HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
inputConfigInfoBuffer,
Marshal.SizeOf(inputConfigInfoSet),
IntPtr.Zero);
if (ErrorCode.AlreadyExists == retVal)
{
retVal = NativeMethods.HttpDeleteServiceConfiguration(
IntPtr.Zero,
HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
inputConfigInfoBuffer,
Marshal.SizeOf(inputConfigInfoSet),
IntPtr.Zero);
if (ErrorCode.Success == retVal)
{
retVal = NativeMethods.HttpSetServiceConfiguration(
IntPtr.Zero,
HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
inputConfigInfoBuffer,
Marshal.SizeOf(inputConfigInfoSet),
IntPtr.Zero);
}
}
Marshal.FreeHGlobal(inputConfigInfoBuffer);
NativeMethods.HttpTerminate(HttpApiConstants.InitializeConfig, IntPtr.Zero);
}
if (ErrorCode.Success != retVal)
{
throw new Win32Exception(Convert.ToInt32(retVal, CultureInfo.InvariantCulture));
}
}
示例12: GetVMnameSid
public static SecurityIdentifier GetVMnameSid(string VMName)
{
ManagementObjectCollection queryCollection;
SecurityIdentifier sid = null;
try
{
ManagementScope scope = new ManagementScope(@"\\.\root\virtualization\v2");
scope.Connect();
string querystr = "SELECT * FROM Msvm_ComputerSystem where ElementName=\"" + VMName + "\"";
ObjectQuery query = new ObjectQuery(querystr);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
queryCollection = searcher.Get();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
//Console.WriteLine("Name,GUID,PID");
try
{
foreach (ManagementObject vm in queryCollection)
{
try
{
// display VM details
//Console.WriteLine("{0},{1},{2}", vm["ElementName"].ToString(),
// vm["Name"].ToString(), vm["ProcessID"].ToString());
string concat = "NT VIRTUAL MACHINE\\" + vm["Name"].ToString();
NTAccount ntaccount = new NTAccount(concat);
sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier));
Console.WriteLine("{0},{1},{2},{3}", vm["ElementName"].ToString(),
vm["Name"].ToString(), vm["ProcessID"].ToString(), sid.ToString());
}
catch (Exception /*e*/)
{
// don't print anything, some entries might miss fields like process id, ignore and move on
//Console.WriteLine(e.ToString());
continue;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
return sid;
}
示例13: GetNoneGroupSID
public static string GetNoneGroupSID()
{
try
{
var objUsersGroup = new NTAccount("None");
return ((SecurityIdentifier)objUsersGroup.Translate(typeof(SecurityIdentifier))).Value;
}
catch
{
throw new Exception("Could not get SID for the local 'None' group. Aborting.");
}
}
示例14: IsInRole
public virtual bool IsInRole(string role)
{
if ((role == null) || (role.Length == 0))
{
return false;
}
NTAccount account = new NTAccount(role);
SecurityIdentifier sid = NTAccount.Translate(new IdentityReferenceCollection(1) { account }, typeof(SecurityIdentifier), 0)[0] as SecurityIdentifier;
if (sid == null)
{
return false;
}
return this.IsInRole(sid);
}
示例15: GetSIDFromUsername
/// <summary>
/// Returns the SID of the user with the username
/// Throws an exception of something does not work
/// </summary>
/// <param name="username">Username</param>
/// <returns>SID as String</returns>
public static string GetSIDFromUsername(string username)
{
try
{
var account = new NTAccount(username);
var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
return sid.ToString();
}
catch (Exception ex)
{
Logger.Log(ex, String.Format("Unable to get SID for username {0}",username));
throw;
}
}