Vladimir Moldovan
Vladimir Moldovan

Reputation: 100

Configure authentication for http requests from web.config file

So I have a bunch of requests that I need to do from c# to a web api and they need basic authentication. I know I can do something like this:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");

        String username = "abc";
        String password = "123";
        String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
        httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

but I don't want to manually add the credentials into the header for every request. I'm wondering if there's a way through which I can globally authenticate all my requests (from web.config, perhaps something similar to connectionStrings for sql connections?).

Upvotes: 2

Views: 3172

Answers (2)

ChrisS
ChrisS

Reputation: 376

You could create a class that inherits HttpClient, and as you suggest gets the UserName and Password from the web.config

public class AuthenticatedClient : HttpClient
{
    public AuthenticatedClient()
    {
        string password = ConfigurationManager.AppSettings["Password"];
        string userName = ConfigurationManager.AppSettings["UserName"];
        string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));

        BaseAddress = new Uri("http://url");
        DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
        DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
}

and in the web.config

<appSettings>
    <add key="UserName" value="abc" />
    <add key="Password" value="123" />
</appSettings>

then wherever you want to make a request use it just like the standard HttpClient

StringContent stringContent = new StringContent("json request string", UnicodeEncoding.UTF8, "application/json");

using (var client = new AuthenticatedClient())
{
   HttpResponseMessage response = await client.PostAsync("/api/whatever", stringContent);
}

Upvotes: 1

John Ephraim Tugado
John Ephraim Tugado

Reputation: 765

If you want your credentials to be static yet can changeable then you can go on with your idea and add the username and password to the web.config app settings. Please refer to this

You can create a utility method that adds the Authorization header.

public static void AddAuthorizationHeader(ref HttpWebRequest request)
{
    string username = //load value from web.config
    string password = //load value from web.config
    string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
}

So just use it like this for all your http web requests that needs that header..

HttpWebRequest request = new HttpWebRequest();
UtilityClass.AddAuthorizationHeader(ref request);
request.ContentType = "application/json";
request.Method = "POST";

P.S. i'm using my mobile phone so sorry for this poor answer. But I guess this is what you need.

Upvotes: 0

Related Questions