只有我的网站才能调用Web Api

时间:2016-12-08 04:00:53

标签: c# asp.net .net asp.net-web-api

我有一个网站和网络API。我想要的是当有人调用我的web api方法时,它应该拒绝请求。但我的网站调用web api然后它应该处理和响应。它不仅仅是CORS,而且当我的网站C#代码从我的网站请求时,web api应该响应。不应回复其他域请求。我使用的是asp.net MVC 5,与web api相同。我怎样才能完成任务。还需要知道如何使我的web api能够回应我网站上的cors请求以及我的web api如何回应我网站上的网站C#请求?

1 个答案:

答案 0 :(得分:3)

您可以限制令牌,IP地址或两者。

例如,

public class TokenValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext == null)
            throw new ArgumentNullException("actionContext");

        var authorization = actionContext.Request.Headers.Authorization;
        if (authorization != null)
        {
            var authToken = authorization.Parameter;
            var token = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

            if ("Authorized Token" == token)
                return;
        }

        actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
}

public class IpHostValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var context = actionContext.Request.Properties["MS_HttpContext"] 
           as HttpContextBase;
        string ipAddress = context.Request.UserHostAddress;

        if (ipAddress == "Authorized IP Address")
            return;

        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
        {
            Content = new StringContent("Unauthorized IP Address")
        };
    }
}

用法

您可以将这些过滤器放在每个控制器上,也可以使用全局过滤器。

public class FilterConfig
{
    public static void RegisterGlobalFilters(HttpFilterCollection filters)
    {
        filters.Add(new TokenValidationAttribute());
        filters.Add(new IpHostValidationAttribute());
    }
}

客户助手

public static HttpClient GetHttpClient()
{
    var client = new HttpClient(new RetryHandler(new HttpClientHandler()));

    client.BaseAddress = new Uri("API URL");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));

    var bcreds = Encoding.ASCII.GetBytes("Authorized Token Same As Server");
    var base64Creds = Convert.ToBase64String(bcreds);
    client.DefaultRequestHeaders.Add("Authorization", 
        "Basic " + base64Creds);

    return client;
}

客户端使用

using (var client = GetHttpClient())
{
    HttpResponseMessage response = await client.GetAsync(requestUri);

    if (response.IsSuccessStatusCode)
    {
        result = await response.Content.ReadAsAsync<IList<T>>().ConfigureAwait(false);
    }
    else
    {
        throw new Exception(response.ReasonPhrase);
    }
}

如果您想要更高的安全性,可能需要查看公钥和私钥方法。