Can I use .NET's HttpClient to hit an Azure Mobile service?
How do I authenticate with the Mobile Service's own baked in custom Authentication/Authorization patterns with the HttpClient?
This always returns 401, because I'm not passing in any authentication credentials:
var client = new HttpClient();
var response = client.GetAsync("http://localhost:49190/api/test").Result;
Furthermore, how come when I use the Mobile Service Client, why does my application key, master key, or user auth key always return (401) Unauthorized?
Client:
var mobileClient = new MobileServiceClient("http://localhost:49190/", "[my key]");
var response = mobileClient.InvokeApiAsync("test").Result;
Service Side:
[AuthorizeLevel(AuthorizationLevel.Application)]
public class TestController : ApiController
{
public ApiServices Services { get; set; }
// GET api/Test
public string Get()
{
Services.Log.Info("Hello from custom controller!");
return "Hello";
}
}
"Can I use .NET's HttpClient to hit an Azure Mobile service?" The short answer is yes. The simple way is to add a this to the headers on the client:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-ZUMO-APPLICATION", "[my key]");
Be careful though, if you're using a locally hosted version you'll want to make sure you've...
Forced the service to think it's hosted so that it enables Authentication.
(in App_Start/WebApiConfig.cs: config.SetIsHosted(true);
Added the application key and master key to the web.config:
<appSettings>
<add key="MS_MasterKey" value="[your master key]" />
<add key="MS_ApplicationKey" value="[your app key]" />
</appSettings>
Without #1, the authentication across the service will be completely ignored, and therefore you don't know if how you've added authentication in the client is working. Without #2, you can add the key to the client (that you get from Azure) all you want, but it will always return 401. This may be the answer to the second question posted about using the MobileServiceClient
always returning 401.
Lastly, there are three different headers you can use in total. You use each one with each different level of authorization. From this MSDN doc:
Author note: I personally struggled with getting this to work, and with either limited or missing documentation out there for this specific style, I wanted to write this Q/A. Please let me know if you think I should add anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With