简体   繁体   English

在 C# 中使用 HttpClient 进行基本身份验证,无需硬编码密码

[英]Basic authentication with HttpClient in C# without hardcoding password

I am invoking an API with System.Net.Http.HttpClient and is using Basic Authentication.我正在使用 System.Net.Http.HttpClient 调用 API 并使用基本身份验证。 The client is running as a windows service.客户端作为 windows 服务运行。 I am looking for a way to trigger the API with basic authentication.我正在寻找一种通过基本身份验证触发 API 的方法。

I know I can use something like我知道我可以使用类似的东西

var base64String=; client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", EncodeBase64(GetBytes("username:password")));

I don't want to input, username & pasword or base 64 encoded credentials.我不想输入用户名和密码或 base 64 编码凭据。 Is it possible to get the credentials of current user, so that the credentials are not maintained in the app(in config files or code).是否可以获取当前用户的凭据,以便凭据不在应用程序中维护(在配置文件或代码中)。

I don't want to maintain credentials in the application, since it is a tedious process during set up to edit the config file(or wherever the credentials are maintained) and add the credentials, also it is not secure to have credentials in the config file as it is human readable.我不想在应用程序中维护凭据,因为在设置期间编辑配置文件(或维护凭据的任何位置)和添加凭据是一个繁琐的过程,而且在配置中拥有凭据也不安全文件,因为它是人类可读的。

I'd advice you not to hard code these credentials and preferably to get them from things such as a database where they are safely hashed.我建议您不要对这些凭据进行硬编码,最好从诸如安全散列的数据库之类的东西中获取它们。 If you simply don't want to input the username & password or the base 64 encoded equivalant, then I suggest you look into other options aside from basic authentication.如果您只是不想输入用户名和密码或 base 64 编码等效项,那么我建议您查看除基本身份验证之外的其他选项。

Other options could be windows authentication, azure or even client certificates.其他选项可能是 windows 身份验证、azure 甚至是客户端证书。

You can get current user from claims.您可以从声明中获取当前用户。 Something like就像是

string userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM