0

I want to make API(s) using ASP.NET WEB API which should be private or protected. Using the API(s) I am planning to make Xamarin application and a MVC Website. Only the Apps can use the API(s), otherwise if anyone get the API(s) then he/she can retrieve data using the API(s). I don't want so!

How can I do it? I need some suggestion.

Ritwick Dey
  • 18,464
  • 3
  • 24
  • 37
  • `OAuth2` is also a good option for this, see http://stackoverflow.com/questions/26755573/how-to-implement-oauth2-server-in-asp-net-mvc-5-and-web-api-2 – G0dsquad Dec 30 '16 at 16:40

2 Answers2

0

You can secure you api with API Key Authentication mechanism. Here is a good tutorial

Ahmar
  • 3,717
  • 2
  • 24
  • 42
0

Starting go inside your global.asax.cs file and add

GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthHandler())

Create a class AuthHandler in your project and make that class interface with DelegatingHandler:

public class AuthHandler: DelegatingHandler

Create two methods within your AuthHandler class called ValidateCredentials and SendAsync. The SendAsync method is overridded.

private bool ValidateCredentials(AuthenticationHeaderValue authVal){}
protected override async Task<HttpResponseMessage> SendAsync(HttpResponseMessage request, CancellationToken cancelTok){}

When a class or method has the Authorize filter applied, the MessageHandler in your global.asax is called which calls the Auth handler you created, for example:

[Authorize] 
public class SomeController : ApiControler{}

So whats left is the actual authentication of the user. You need to get the header value (placed by the client application), decode it and check it against your database or whatever you use.

private bool ValidateCredentials(AuthenticationHeaderValue authVal)
{
    try{
        string decodedHeader = new Classes.Strings().decode(authVal);
        this.user = // some query to check against database goes here
        return true;
    }
    catch{
        // some type of error control here
        return false
    }
}
 protected override async Task<HttpResponseMessage> SendAsync(HttpResponseMessage request, CancellationToken cancelTok)
{
    if(ValidateCredentials(request.Headers.Authorization))
    {
        // store user here to use around the api on this request
    }
}

So in short HTTP needs to store your authentication header value. Use that value on each request to filter any class or function you require authentication on. Next, I would read up on http headers, specifically the Authentication header value.

Bjt1776
  • 189
  • 3
  • 15