سؤال

I have a continuously scheduled web job that's monitoring a message queue, pulling messages off and calling a Web API on the peer Web Site to process the messages (in this case using SignalR to send notifications to appropriate users).

What would be the best way in this case to call the web API securely? The API being hosted in the web site is obviously exposed otherwise. Perhaps something using Basic Auth or storing a security token in config and passing it from the job to the web API. Or creating a custom AuthorizeAttribute?

Ant thoughts on securing the Web API call from the WebJob would be much appreciated. The API should only be callable from the WebJob.

UPDATE: Something like this perhaps?

First I declare this class;

public class TokenAuthenticationHeaderValue : AuthenticationHeaderValue
{
    public TokenAuthenticationHeaderValue(string token)
        : base("Token", Convert.ToBase64String(Encoding.UTF8.GetBytes(token)))
    { }
}

Then the caller (the WebJob) uses this class to set an auth header when making the HTTP request;

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(/* something */);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new TokenAuthenticationHeaderValue("TOKEN FROM CONFIG"); 
    // ....

Over in the Web API we check the request looking for the expected token in the auth header, currently the code is pretty ugly but this could be put into a custom 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's naughty!");
    }
    // All OK, carry on.

So this way the WebJob calls the Web API on the peer web site and security is achieved by passing a token that is securely held in the Azure configuration, both the Site and Job have access to this token.

Any better ideas?

هل كانت مفيدة؟

المحلول

Sounds like Basic Authentication would be fine for your scenario.

Great tutorial here: Basic Authentication

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top