-1

I wanwt to add a layer of security via certificate to access a hosted ASP.NET WebAPI.

I want only those clients who have installed the certificate in their machine to have access to that WebAPI.

Can anyone provide me a way to achieve this behavior?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Abbas Galiyakotwala
  • 2,949
  • 4
  • 19
  • 34
  • 2
    I just Googled 'web api 2 certificate authentication' and got a page full of results including a few stackoverflow pages. Did you try that? – matt_lethargic Aug 09 '17 at 09:39
  • It seems that this guy went through a similar plight and did an amazing job documenting his steps: https://stackoverflow.com/questions/35582396/how-to-use-a-client-certificate-to-authenticate-and-authorize-in-a-web-api – Travis Acton Aug 15 '17 at 16:00

2 Answers2

1

You can configure IIS to require client certificates without writing a single line of code. Just follow these instructions, specifically these:

  1. Click SSL settings in the middle panel and select Require SSL and Require for Client certificates.

  2. Double click the Authentication icon and disable all the Authentication method.

  3. Make sure the IIS Client Certificate Mapping Authentication is installed.

  4. Click the Configuration Editor in the middle panel and set the one to one mappings refer to this link

John Wu
  • 50,556
  • 8
  • 44
  • 80
0

Just as suggested in comments, a quick google search could lead to interesting results.

Nevertheless a possible solution is the implementation proposed in the following Microsoft article :

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            base.OnAuthorization(actionContext);
        }
    }
}

You would then decorate your ApiController action :

public class SomeController : ApiController
{
    [RequireHttps]
    public HttpResponseMessage Get() { ... }
}
John-Philip
  • 3,392
  • 2
  • 23
  • 52