5

I'm trying to use the Reddit API (https://github.com/reddit-archive/reddit/wiki/OAuth2) in my ASP.NET Core MVC app, and to obtain a token I have to make a POST to a URI with HTTP Basic Authorization (username and password being a client id and secret). Currently I use this code:

public async Task<HttpResponseMessage> HttpPost(string uri, string value)
{
    HttpClient httpClient = new HttpClient();
    HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri, new StringContent(value));
    return httpResponseMessage;
}

However, this doesn't use the authorization. How can I add authorization? I tried looking at the documentation for HttpClient.PostAsync and HttpContent, but I don't see anything relevant.

Merlin04
  • 1,837
  • 4
  • 23
  • 27
  • Possible duplicate of [Setting Authorization Header of HttpClient](https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient) – Ed Bangga Aug 29 '19 at 01:28

1 Answers1

13

You will need to create a base64 encoded string with format: username:password. Then add it to Authorization header for Http Request.

Example:

using (var client = new HttpClient { BaseAddress = new Uri("https://baseUrl") })
{
 var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes("username:password"));

 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
 var response = await client.PostAsync(requestUri, new StringContent(value));
}
Mort
  • 15
  • 5
KrishnaDhungana
  • 2,604
  • 4
  • 25
  • 37