c# - CredRead() 无法跨登录 session 工作

标签 c# security credentials credential-manager

我正在根据 this answer 使用 Credential Manager API .引用相关代码片段:

public static Credential ReadCredential(string applicationName)
{
    IntPtr nCredPtr;
    bool read = CredRead(applicationName, CredentialType.Generic, 0, out nCredPtr);
    if (read)
    {
        using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
        {
            CREDENTIAL cred = critCred.GetCredential();
            return ReadCredential(cred);
        }
    }

    return null;
}

它工作得很好,除了当我注销我的 Windows 帐户然后再次登录时,CredRead() 返回 false 并且 Marshal.GetLastWin32Error() 给我 1168,或 ERROR_NOT_FOUND

为什么会有这种行为? Credential Management API 是否仅适用于当前 session ,还是我做错了什么?

编辑:this question下方的评论说:

The documents for the credential management APIs seem to indicate that these credentials are associated with a logon session. Perhaps LogonUser results in a new logon session, so the credentials don't exist there.

但是,我还没有找到任何证据表明凭据管理是特定于 session 的。如果是这样的话,我认为这将毫无用处。

编辑 2:仅作记录,如果您需要获取指示 CredRead() 失败原因的错误编号,请检查 this article 中的 ReadCred() 方法。 .

最佳答案

您可以通过设置 Persist 属性来配置凭据的持久化方式

来自 MSDN ( http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788(v=vs.85).aspx )

CRED_PERSIST_SESSION
CRED_PERSIST_LOCAL_MACHINE
CRED_PERSIST_ENTERPRISE

关于c# - CredRead() 无法跨登录 session 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22528292/

相关文章:

c# - Q : SignalR authentication with . NET 客户端在本地工作但在服务器上不工作

powershell - 使用 PowerShell 向服务添加凭据

c# - 从 XElements 列表创建 XDocument

javascript - 关于同源政策....我可以这样做吗?

docker - 凭证不适用于 "docker login"

ruby-on-rails - 任何人都在使用 detrusion.com,用于 ruby​​ on rails 的 Web 应用程序防火墙

c - 这是缓冲区溢出的工作方式吗?

c# - 如何从数据库中获取最接近的日期时间?

c# - .net core 2.1 测试 API Controller 缺少 AspNetCore.Mvc 引用

c# - 从 C# 中的接口(interface)创建对象