如何不使用硬编码凭据

问题描述 投票:0回答:1

我有一个使用 VS 实现的 Winforms C# 程序。该程序用于以管理员身份运行进程。到目前为止,凭证都是硬编码的。

但我问自己,构建过程中是不是可以得到输入提示。

凭据在构建的程序中没有问题,但我不想将凭据保存在源代码中。

所以我想一定有一种方法可以让 VS 在构建过程中要求输入用户名和密码。

这可能吗?

c# visual-studio winforms
1个回答
0
投票

以下示例展示了如何在构建过程中提示用户输入凭据并将其保存到应用程序配置文件中。

首先,您可以将 appSettings 节点添加到应用程序的配置文件(例如 app.config 或 web.config)中以保存凭据信息:

<appSettings>
   <add key="Username" value=""/>
   <add key="Password" value=""/>
</appSettings>

然后,创建一个简单的表单来提示用户输入用户名和密码并将其保存到配置文件中:

using System;
using System.Configuration;
using System.Windows.Forms;

namespace YourNamespace
{
     public partial class LoginForm : Form
     {
         public LoginForm()
         {
             InitializeComponent();
         }

         private void btnLogin_Click(object sender, EventArgs e)
         {
             
             string username = txtUsername.Text;
             string password = txtPassword.Text;

             //Save credentials to configuration file
             SaveCredentials(username, password);

          
             this.Close();
         }

         private void SaveCredentials(string username, string password)
         {
             //Update username and password in configuration file
             Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             config.AppSettings.Settings["Username"].Value = username;
             config.AppSettings.Settings["Password"].Value = password;
             config.Save(ConfigurationSaveMode.Modified);
             ConfigurationManager.RefreshSection("appSettings");
         }
     }
}

当你的应用程序启动时,首先检查配置文件中是否存在用户名和密码。如果不存在,则显示登录窗口:

using System;
using System.Configuration;
using System.Windows.Forms;

namespace YourNamespace
{
     static class Program
     {
         [STAThread]
         static void Main()
         {
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);

            
             string username = ConfigurationManager.AppSettings["Username"];
             string password = ConfigurationManager.AppSettings["Password"];

             if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
             {
                
                 LoginForm loginForm = new LoginForm();
                 Application.Run(loginForm);
             }
             else
             {
                 
                 Application.Run(new Form1());
             }
         }
     }
}

© www.soinside.com 2019 - 2024. All rights reserved.