'D365 OData request returns 403 error but works in browser. What am I missing?

My code's pretty straight forward:

var header = OAuthHelper.GetAuthenticationHeader(config, true);

var c = new WebClient();
c.Headers[OAuthHelper.OAuthHeader] = header;
// {Authorization: Bearer reallylongstring}
var res = c.DownloadString(D365BaseUrl + "/data/CustomersV2");

But I get a 403 Error:

System.Net.WebException
HResult=0x80131509
Message=Remote Server returned an Error: (403) Forbidden.
Source=System
StackTrace:
 at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
 at System.Net.WebClient.DownloadString(Uri address)
 at System.Net.WebClient.DownloadString(String address)
 at ODataTest.Program.Main(String[] args) in C:\mypath\ODataTest\Program.cs:line 35

But when I open that url in the browser it works.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source