سؤال

I am trying to search for this question but dont have much luck.

The idea is to design a web api which initially will only consumed by internal web front end (for e.g asp.net MVC application). The reason being I dont have much time to spend on making the webapi secure now (may be in future the application will be exposed to the www).

I have tried DotNetOpenAuth but it doesnt have good documentation.

So the question is how to secure web api without much complicated security code so that it can securely communicate with my ASP.NET MVC application?

Or is this a totally wrong approach. Perhaps I should secure my webapi in the beginning?

Anyway does anyone knows how to achieve this? Any article or comments?

Thanks

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

المحلول

I would create a simple DelegatingHandler that will be called before each requests

public class AuthorizationDelegatingHandler : DelegatingHandler
{
    private const string API_KEY = "8139E7541722F5D91ED8FB15165F4"

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        if (request.Headers.Authorization == null)
            return request.CreateResponse(HttpStatusCode.Unauthorized);

        if (request.Headers.Authorization.Scheme != "Basic")
            return request.CreateResponse(HttpStatusCode.Unauthorized);

        var authToken = request.Headers.Authorization.Parameter;

        var apiKey = Encoding.UTF8.GetString(Convert.FromBase64String(authToken))
            .Split(':')
            .FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));

        if (string.IsNullOrWhiteSpace(apiKey) || apiKey != API_KEY)
           return request.CreateResponse(HttpStatusCode.Unauthorized);

        return await base.SendAsync(request, cancellationToken);
    }
}

I know that using a static token is maybe not the best thing, but it should give you an idea.

In your application bootstrap, you will need to register this handler

GlobalFilters.Filters.Add(new AuthorizationDelegatingHandler());

Then when you will call this API, you can add the Authorization header using Basic scheme.

Each request that does not have this header will return an Unauthorized response.

The client should call the API this way:

var client = new HttpClient
{
    BaseAddress = new Uri(API_URL)
};

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Basic",
    Convert.ToBase64String(Encoding.UTF8.GetBytes("8139E7541722F5D91ED8FB15165F4:")));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top