Reynaldi
Reynaldi

Reputation: 1165

How to make sure that all call to asp web api is authorized?

I'm building an saas application using asp web api 2 and asp identity. This api will be consumed by web, mobile and desktop applications. How do i make sure that all calls to my web api method is authorized? In web, we can ask user to login before going to certain page, but how bout mobile/desktop? Does user need to provide login and password on each call? Are there better solution for this? I've been searching and havent found any article about this. A sample or articles will be much appreciated.

Upvotes: 0

Views: 1068

Answers (1)

rik.vanmechelen
rik.vanmechelen

Reputation: 1914

Usually when using api's as a back-end you have to authenticate the user on every request.
(it actually also happens with other frameworks, such as mvc.net, but they keep track of the user using cookies which are send back and forth with every request)

I would suggest you use token based authentication (e.g. OAuth). In such a case you set the token in the header of the request. This token will be used to authenticate (and potentially authorize) the user.

If you need more info i can always explain it a bit more.

== Edit: Added Code sample ==

You could use a request handler to validate that the header of the request includes a valid token:

public class AuthorizationHeaderHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage pRequest, CancellationToken pCancellationToken)
    {
        IEnumerable<string> apiKeyHeaderValues = null; 
        if (!pRequest.Headers.TryGetValues("Authorization", out apiKeyHeaderValues)
            || !TokenRepo.IsVallidToken(apiKeyHeaderValues))
        {
            var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
            {
                Content = new StringContent("{\"error\": \"invalid_token\"}")
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return Task.Factory.StartNew(() => response);
        }
        return base.SendAsync(pRequest, pCancellationToken);
    }
}

All you have to do is keep which token is associated with which user, and make sure tokens have an expiration period. Once this is passed, it is also not valid anymore.

I hope this clarifies it a bit. Again, if you have more questions, do not hesitate to ask.

Upvotes: 1

Related Questions