I have a constantly scheduled web task that monitors the message queue, disables messages, and calls the web API on the peer website to process messages (in this case, using SignalR to send notifications to the appropriate users).
What would be the best way to safely call the web API in this case? The API hosted on the website is clearly displayed otherwise. Maybe something is using Basic Auth or storing the security token in the configuration and passing it from the job to the web API. Or create a custom attribute AuthorizeAttribute?
Ant thoughts on protecting the WebJob API call from WebJob will be greatly appreciated. The API should only be called from WebJob.
UPDATE: Is something like this possible?
First I declare this class;
public class TokenAuthenticationHeaderValue : AuthenticationHeaderValue { public TokenAuthenticationHeaderValue(string token) : base("Token", Convert.ToBase64String(Encoding.UTF8.GetBytes(token))) { } }
The caller (WebJob) then uses this class to set the auth header when executing an HTTP request;
using (var client = new HttpClient()) { client.BaseAddress = new Uri(); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new TokenAuthenticationHeaderValue("TOKEN FROM CONFIG");
In the web API, we test a query looking for the expected token in the auth header, the code is currently pretty ugly, but it can be placed in a user attribute;
public HttpResponseMessage Post([FromBody]TheThing message) { var authenticationHeader = Request.Headers.Authorization; var token = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationHeader.Parameter)); if (authenticationHeader.Scheme != "Token" || token != "TOKEN FROM CONFIG") { return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No, no, no. That naughty!"); }
Thus, WebJob calls the web API on a peer-to-peer website, and security is achieved by passing a token that is held securely in the Azure configuration, and both the site and Job have access to this token.
Any better ideas?