Comment récupérez-en-t-on la connexion Windows Sid dans C # .NET? (pas l'utilisateur SID, mais le nouveau unique pour chaque session) P>
4 Réponses :
System.Security.Principal.windowSidentity.getCurrent (). Utilisateur.accountDomansid - Peut faire le tour? P>
C'est pas i> l'identifiant de session de connexion Silverskin a demandé à propos de
Je pense que le SID de l'utilisateur reste inchangé entre des sessions, mais pour chaque connexion, un jeton est créé, il devrait être possible d'accéder à cette ... GetCurrent (). Utilisateur.Token?
Le jeton est en effet ce dont j'ai besoin, mais je dois convertir en unid utilisable.
De quoi en avez-vous besoin? L'impersonnation et d'autres choses devraient être disponibles à travers le jeton.
J'ai une application externe qui crée un tuyau nommé avec le logon UID. Sans cela, je ne peux pas déterminer le nom du tuyau.
Je crains que vous fassiez avoir recours à P / invoke. Il y a un exemple de comment le faire à pinvoke.net (voir le bas de La page):
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace LinqTest
{
public class ClsLookupAccountName
{
public const uint SE_GROUP_LOGON_ID = 0xC0000000; // from winnt.h
public const int TokenGroups = 2; // from TOKEN_INFORMATION_CLASS
enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin
}
[StructLayout(LayoutKind.Sequential)]
public struct SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_GROUPS
{
public int GroupCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public SID_AND_ATTRIBUTES[] Groups;
};
// Using IntPtr for pSID instead of Byte[]
[DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool ConvertSidToStringSid(IntPtr pSID, out IntPtr ptrSid);
[DllImport("kernel32.dll")]
static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(
IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
IntPtr TokenInformation,
int TokenInformationLength,
out int ReturnLength);
public static string GetLogonId()
{
int TokenInfLength = 0;
// first call gets lenght of TokenInformation
bool Result = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenGroups, IntPtr.Zero, TokenInfLength, out TokenInfLength);
IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength);
Result = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenGroups, TokenInformation, TokenInfLength, out TokenInfLength);
if (!Result)
{
Marshal.FreeHGlobal(TokenInformation);
return string.Empty;
}
string retVal = string.Empty;
TOKEN_GROUPS groups = (TOKEN_GROUPS)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_GROUPS));
int sidAndAttrSize = Marshal.SizeOf(new SID_AND_ATTRIBUTES());
for (int i = 0; i < groups.GroupCount; i++)
{
SID_AND_ATTRIBUTES sidAndAttributes = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(
new IntPtr(TokenInformation.ToInt64() + i * sidAndAttrSize + IntPtr.Size), typeof(SID_AND_ATTRIBUTES));
if ((sidAndAttributes.Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID)
{
IntPtr pstr = IntPtr.Zero;
ConvertSidToStringSid(sidAndAttributes.Sid, out pstr);
retVal = Marshal.PtrToStringAuto(pstr);
LocalFree(pstr);
break;
}
}
Marshal.FreeHGlobal(TokenInformation);
return retVal;
}
}
}
Ne fonctionne pas malheureusement. Ça ne renvoie rien. Selon ceci ( msdn.microsoft.com/fr- US / Bibliothèque / AA379626% 28VS.85% 29.aspx ), il ne fonctionne que sur Terminal Server, il est donc possible que cela ne soit pas l'identifiant de session dont j'ai besoin.
J'ai ajouté une autre version du code, cela fonctionne sur ma machine. S'il vous plaît n'hésitez pas à me demander si quelque chose n'est pas clair.
Merci! Celui-ci fonctionne parfaitement. J'ai utilisé Tokenlogonid au lieu de groupes de token, mais cela ne fonctionne que pour Windows Vista et 7.
C'est très utile, merci. Pourquoi utilisez-vous tokeninformation.toint64 () + i * sidandattrsize + intptr.size code> au lieu de tokeninformation.toint64 () + i * sidandattrsize + 4 code>, étant donné que token_groups.groupcount est un dword? Est-ce intentionnel? (FYI ma question associée ici: Stackoverflow.com/questions/6066650 )
Je sais que c'est un ancien post. Il suffit de courir dans ce problème car je devais obtenir l'ID de session ICA et l'ID de session RDP pour avoir un programme de collecter les variables correctes pour chaque type de connexion à distance. L'ID de session actuel est situé dans Regedit HKEY_CURRENT_USER \ REMOTE *. Comme je ne pouvais trouver aucune alternative à WTS, je pose ma solution ici.
// Prints out ICA or RDP session ID of current user
using System;
using Microsoft.Win32;
namespace ViaRegedit
{
class Program03
{
static void Main(string[] args)
{
// Obtain an instance of RegistryKey for the CurrentUser registry
RegistryKey rkCurrentUser = Registry.CurrentUser;
// Obtain the test key (read-only) and display it.
RegistryKey rkTest = rkCurrentUser.OpenSubKey("Remote");
foreach (string valueName in rkTest.GetSubKeyNames())
{
//Getting path to RDP/Citrix session ID
string RDPICApath = "";
if (rkTest.OpenSubKey(valueName) != null && rkTest.OpenSubKey(valueName) != null) { RDPICApath = rkTest.OpenSubKey(valueName).ToString(); }
Console.WriteLine("Getting CurrentUser ICA-RDP path from string = " + RDPICApath);
//Seperating RDPICApath to get session number
string RDPICAnumber = RDPICApath.Substring(RDPICApath.LastIndexOf('\\') + 1);
Console.WriteLine("Current User RDPICAnumber = " + RDPICAnumber);
}
rkTest.Close();
rkCurrentUser.Close();
Console.ReadLine();
}
}
}
Je viens de passer longtemps à obtenir le SID à l'aide de Token_User et ainsi de suite, puis découvrez un raccourci en C #. Vous devez toujours obtenir le processus de processus (par exemple, https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.handle?view=netcore-3.1 ), puis le jeton avec p / invoke: < PRE> XXX PRE>
Mais une fois que vous avez le jeton, vous n'avez pas besoin de faire de Nasty ... et boom Vous pouvez obtenir toutes les informations que vous souhaitez (INC SID) pour l'utilisateur de WinID. P> N'oubliez pas à getTokenInformation (hotes, token_information_class.token_information_class.token_information ... code> des choses que vous venez d'utiliser: p> CLOSEHANDLE (HTTHTEND) CODE> et sur HPROCESS par la suite! P> P>
Dans Windwos Environnement Sid signifie identifiant de sécurité, pas ID de session. Pour obtenir une carte d'identité de session utiliser
system.diagnostics.process.getcurrentProcess (). SéditionId code> Pour plus de détails, voir Ma réponse ici