简体   繁体   中英

Basic authentication with HttpClient in C# without hardcoding password

I am invoking an API with System.Net.Http.HttpClient and is using Basic Authentication. The client is running as a windows service. I am looking for a way to trigger the API with basic authentication.

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. 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.

Other options could be windows authentication, azure or even client certificates.

You can get current user from claims. Something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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