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.

1

1 Answer 1

15

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)); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this is correct for HTTP Basic Authentication. There is no need to go into OAuth details as many suggested solutions do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.