Delphi 2009中如何获取当前登录用户,包括域?

发布于 2024-08-12 04:22:48 字数 143 浏览 1 评论 0原文

我需要获取当前登录的用户名?当我从在 Windows 身份验证模式下工作的 ASP.NET 调用代码时,我需要它正常工作。即我不想在这种情况下获得 ASPNET 用户,而是模拟用户。这与我之前的问题相关。我尝试的一切都会返回ASPNET

I need to get the current logged on username? I need this to work properly when I call the code from ASP.NET which is working in Windows Authentication mode. i.e. I do not want to get the ASPNET user in that circumstance, but the impersonated user. This is related to my earlier question. Everything I try returns ASPNET.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

破晓 2024-08-19 04:22:48

在您的另一个问题中,您写道您将 ASP.NET 配置为使用 Windows 身份验证进行模拟:

 <system.web>
    ...
    <authentication mode="Windows"/>
    <identity impersonate="true"/>
    ...
 </system.web>

ASP.NET 应用程序是否显示正确的凭据(用户和域)?

您是否使用正确的身份上下文调用Delphi函数,例如

WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
try
{
    ctx = winId.Impersonate();
    // call Delphi function, passing the identity context
}
catch
{
}
finally
{
    if (ctx != null)
        ctx.Undo();
}

更新:

如果从Web表单页面的代码隐藏中调用COM对象,您可以尝试将Web表单页面的ASPCOMPAT属性设置为true。

请参阅:

“身份”标签确保
执行请求的线程(MTA
线程)将模拟其安全性
上下文中指定的用户
标签,但我们的 STA COM 对象
最终是在默认情况下创建的
未模拟的 STA 线程,
使其获取安全上下文
进程的(IUSR_XXX –
所有用户中最没有权力的用户)。

In your other question you wrote that you configured ASP.NET to use Windows authentication with impersonation:

 <system.web>
    ...
    <authentication mode="Windows"/>
    <identity impersonate="true"/>
    ...
 </system.web>

Does the ASP.NET application show the correct credentials (user and domain)?

Are you invoking the Delphi function using the correct Identity context, like

WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
try
{
    ctx = winId.Impersonate();
    // call Delphi function, passing the identity context
}
catch
{
}
finally
{
    if (ctx != null)
        ctx.Undo();
}

Update:

If the COM abject is called from the code behind for a web form page, you can try to set ASPCOMPAT property of the web form page to true.

See:

The "identity" tag makes sure that the
thread executing the request (the MTA
thread) will impersonate its security
context to the user specified in the
tag but our STA COM object
eventually was created on the default
STA thread which was not impersonate,
causing it to get the security context
of the process (which was IUSR_XXX –
the least powerful user of all).

原野 2024-08-19 04:22:48

也许您的 IADsWinNTSystemInfo 方法(来自链接的上一个问题)返回当前进程的帐户信息,但 ASP.NET 是在线程级别模拟?

试试这个:

type
  PTokenUser = ^TTokenUser;
  TTokenUser = packed record
    User: SID_AND_ATTRIBUTES;
  end;

function GetCurrentUserName(out DomainName, UserName: string): Boolean;
var
  Token: THandle;
  InfoSize, UserNameSize, DomainNameSize: Cardinal;
  User: PTokenUser;
  Use: SID_NAME_USE;
  _DomainName, _UserName: array[0..255] of Char;
begin
  Result := False;
  DomainName := '';
  UserName := '';

  Token := 0;
  if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, Token) then
  begin
    if GetLastError = ERROR_NO_TOKEN then // current thread is not impersonating, try process token
    begin
      if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token) then
        Exit;
    end
    else
      Exit;
  end;
  try
    GetTokenInformation(Token, TokenUser, nil, 0, InfoSize);
    User := AllocMem(InfoSize * 2);
    try
      if GetTokenInformation(Token, TokenUser, User, InfoSize * 2, InfoSize) then
      begin
        DomainNameSize := SizeOf(_DomainName);
        UserNameSize := SizeOf(_UserName);

        Result := LookupAccountSid(nil, User^.User.Sid, _UserName, UserNameSize, _DomainName, DomainNameSize, Use);

        if Result then
        begin
          SetString(DomainName, _DomainName, StrLen(_DomainName));
          SetString(UserName, _UserName, StrLen(_UserName));
        end;
      end;
    finally
      FreeMem(User);
    end;
  finally
    CloseHandle(Token);
  end;
end;

示例用法:

var
  DomainName, UserName: string;
begin
  if not GetCurrentUserName(DomainName, UserName) then
    RaiseLastOSError;
  Writeln(Format('%s\%s', [DomainName, UserName]));
end;

希望这会有所帮助。

Perhaps your IADsWinNTSystemInfo approach (from the linked previous question) returns current process' account information, but ASP.NET is impersonating on a thread level?

Try this:

type
  PTokenUser = ^TTokenUser;
  TTokenUser = packed record
    User: SID_AND_ATTRIBUTES;
  end;

function GetCurrentUserName(out DomainName, UserName: string): Boolean;
var
  Token: THandle;
  InfoSize, UserNameSize, DomainNameSize: Cardinal;
  User: PTokenUser;
  Use: SID_NAME_USE;
  _DomainName, _UserName: array[0..255] of Char;
begin
  Result := False;
  DomainName := '';
  UserName := '';

  Token := 0;
  if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, Token) then
  begin
    if GetLastError = ERROR_NO_TOKEN then // current thread is not impersonating, try process token
    begin
      if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token) then
        Exit;
    end
    else
      Exit;
  end;
  try
    GetTokenInformation(Token, TokenUser, nil, 0, InfoSize);
    User := AllocMem(InfoSize * 2);
    try
      if GetTokenInformation(Token, TokenUser, User, InfoSize * 2, InfoSize) then
      begin
        DomainNameSize := SizeOf(_DomainName);
        UserNameSize := SizeOf(_UserName);

        Result := LookupAccountSid(nil, User^.User.Sid, _UserName, UserNameSize, _DomainName, DomainNameSize, Use);

        if Result then
        begin
          SetString(DomainName, _DomainName, StrLen(_DomainName));
          SetString(UserName, _UserName, StrLen(_UserName));
        end;
      end;
    finally
      FreeMem(User);
    end;
  finally
    CloseHandle(Token);
  end;
end;

Example usage:

var
  DomainName, UserName: string;
begin
  if not GetCurrentUserName(DomainName, UserName) then
    RaiseLastOSError;
  Writeln(Format('%s\%s', [DomainName, UserName]));
end;

Hope this helps.

肤浅与狂妄 2024-08-19 04:22:48

这是我的 LoadProfile工具,在Delphi 2010中运行良好:

const
  UNLEN = 256; // Maximum user name length

var
  TokenHandle: THandle; // Handle to the Processes' Acces Token
  cbTokenInfo: DWORD; // Size of TokenInfo in Bytes
  pTokenUser: PTOKEN_USER; // Pointer to a TOKEN_USER record

  cchName: DWORD; // Count of characters (length) of the Username array
  cchDomain: DWORD; // Count of characters (length) of the Domainname array
  peUse: DWORD; // Account type for LookupAccountSid

  UserName: array[0..UNLEN] of Char; // Holds the Username
  DomainName: array[0..UNLEN] of Char; // Holds the Domainname
  ComputerName: array[0..UNLEN] of Char; // Hold the Computername


    // Open the Current Process' Token
    OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY or
      TOKEN_IMPERSONATE or TOKEN_DUPLICATE, TokenHandle);

    // Check if we have a valid handle
    if TokenHandle = 0 then
      Exit; 

    { We will use GetTokenInformation to get the user's SID, the first call
      to GetTokenInformation is used to determine how much memory we need to
      allocate }
    GetTokenInformation(TokenHandle, TokenUser, nil, 0, cbTokenInfo);
    // as documented the call should fail with ERROR_INSUFFICIENT_BUFFER
    if (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then
      Exit;

    // Allocate Memory
    pTokenUser :=  HeapAlloc(GetProcessHeap(), 0, cbTokenInfo);
    if (pTokenUser = nil) then
       Exit;

    // Retrieve the user information from the token.
    if ( not GetTokenInformation(TokenHandle, TokenUser, pTokenUser,
      cbTokenInfo, cbTokenInfo)) then
       Exit;

    cchName := Length(UserName);
    cchDomain := Length(DomainName);
    peUse:= SidTypeUser;


    // Use the SID to find User and Domain Name
    Write('LookupAccountSid... ');
    if not LookupAccountSid(nil, pTokenUser^.User.Sid, UserName, cchName,
      DomainName, cchDomain, peUse) then
      Exit;

    // Cleanup
    if (pTokenUser <> nil) then
      HeapFree(GetProcessHeap(), 0, pTokenUser);

    WriteLn('CloseHandle... OK');
    CloseHandle(TokenHandle);

This is a part of the code of my LoadProfile tool, it works well in Delphi 2010:

const
  UNLEN = 256; // Maximum user name length

var
  TokenHandle: THandle; // Handle to the Processes' Acces Token
  cbTokenInfo: DWORD; // Size of TokenInfo in Bytes
  pTokenUser: PTOKEN_USER; // Pointer to a TOKEN_USER record

  cchName: DWORD; // Count of characters (length) of the Username array
  cchDomain: DWORD; // Count of characters (length) of the Domainname array
  peUse: DWORD; // Account type for LookupAccountSid

  UserName: array[0..UNLEN] of Char; // Holds the Username
  DomainName: array[0..UNLEN] of Char; // Holds the Domainname
  ComputerName: array[0..UNLEN] of Char; // Hold the Computername


    // Open the Current Process' Token
    OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY or
      TOKEN_IMPERSONATE or TOKEN_DUPLICATE, TokenHandle);

    // Check if we have a valid handle
    if TokenHandle = 0 then
      Exit; 

    { We will use GetTokenInformation to get the user's SID, the first call
      to GetTokenInformation is used to determine how much memory we need to
      allocate }
    GetTokenInformation(TokenHandle, TokenUser, nil, 0, cbTokenInfo);
    // as documented the call should fail with ERROR_INSUFFICIENT_BUFFER
    if (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then
      Exit;

    // Allocate Memory
    pTokenUser :=  HeapAlloc(GetProcessHeap(), 0, cbTokenInfo);
    if (pTokenUser = nil) then
       Exit;

    // Retrieve the user information from the token.
    if ( not GetTokenInformation(TokenHandle, TokenUser, pTokenUser,
      cbTokenInfo, cbTokenInfo)) then
       Exit;

    cchName := Length(UserName);
    cchDomain := Length(DomainName);
    peUse:= SidTypeUser;


    // Use the SID to find User and Domain Name
    Write('LookupAccountSid... ');
    if not LookupAccountSid(nil, pTokenUser^.User.Sid, UserName, cchName,
      DomainName, cchDomain, peUse) then
      Exit;

    // Cleanup
    if (pTokenUser <> nil) then
      HeapFree(GetProcessHeap(), 0, pTokenUser);

    WriteLn('CloseHandle... OK');
    CloseHandle(TokenHandle);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文