Alx
Alx

Reputation: 6285

Limit access to web api 2 controller in dotnet core mvc project

what is the best way to limit access to a webapi 2 controller within a MVC project to only the hosted App Service?

I have created a endpoint which my MVC client is accessing. The entire application is published to azure through an app service. How can I now protect the endpoint from being called outside of the application context?

Upvotes: 0

Views: 2478

Answers (2)

alwayslearning
alwayslearning

Reputation: 4633

Based on your comments you should consider restructuring your solution.

  • Consider moving your Web API to an independent project. This way your API is decoupled from your MVC app and you can deploy and scale it,if required, independently.
  • Move the MVC client app in it's own independent project
  • For authentication I would consider implementing an authorization server (again in an independent project) that issues tokens to the client (in your case the MVC app) and the client would then access the API using this token. For implementing an auth server you have a couple of options
    • Use the ClientCredentials grant using IdentityServer4
    • Use the OWIN OAuth middleware to implement your auth server with ClientCredentials grant
    • There are other Oauth implementations that you could use too.

Having a dedicated authorization server clearly separates out the identity responsibility allowing you to control access for other future clients and possibly restrict access to only certain endpoints (aka scopes).

Upvotes: 1

Ray Krungkaew
Ray Krungkaew

Reputation: 6965

You could use an API key in the request's header to filter out unwanted request. 1. Implement a customer authorization attribute (AuthorizationFilter) class.

    [HttpPost, AuthorizationFilter]
    public CustomerInfo GetCustomerInfo(CustomerInfoRequest request)
    {
        return Business.GetCustomerInfo(request);
    }

2. In your controller class

    public override void OnAuthorization(HttpActionContext ctx)
    {            
        if (!VerifyHeaders(ctx))
        {
            ctx.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            return;
        }

        base.OnAuthorization(ctx);
    }

    private bool VerifyHeaders(HttpActionContext ctx)
    {
        IEnumerable<string> values = new List<string>();

        //Read the API key from the request header
        ctx.Request.Headers.TryGetValues("ApiKey", out values);
        var apiKey = values?.FirstOrDefault();        

        return CheckApiKey(apiKey);
    }

    private bool CheckApiKey(string apiKey)
    {
        //Verification is done here
        return true;
    }
  1. The request should contain API key which will be verified by "OnAuthorization" method.

enter image description here

Upvotes: 0

Related Questions