How to store and retrieve credentials on Windows using C#

冷暖自知 提交于 2019-11-28 17:19:36
Krzysztof Branicki

You can use the Windows Credential Management API. This way you will ask the user for the password only once and then store the password in Windows Credentials Manager.

Next time your application starts and it needs to use the password it will read it from Windows Credentials Manager. One can use the Windows Credential Management API directly using P/Invoke (credwrite, CredRead, example here) or via a C# wrapper CredentialManagement.


Sample usage using the NuGet CredentialManagement package:

public class PasswordRepository
{
    private const string PasswordName = "ServerPassword";

    public void SavePassword(string password)
    {
        using (var cred = new Credential())
        {
            cred.Password = password;
            cred.Target = PasswordName;
            cred.Type = CredentialType.Generic;
            cred.PersistanceType = PersistanceType.LocalComputer;
            cred.Save();
        }
    }

    public string GetPassword()
    {
        using (var cred = new Credential())
        {
            cred.Target = PasswordName;
            cred.Load();
            return cred.Password;
        }
    }
}

I don't recommend storing passwords in files on client machines. Even if you encrypt the password, you will probably embed the decryption key in the application code which is not a good idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!