只有我的网站调用 Web Api

Having Web Api called by only my website

我有一个网站和网络 api。我想要的是每当有人调用我的网络 api 方法时,它应该拒绝该请求。但是我的网站调用 web api 然后它应该处理并响应。这不仅是 CORS,而且当我的网站 C# 代码从我的网站请求时,网络 api 应该响应。不应响应其他域请求。我正在使用 asp.net MVC 5,与 Web api 相同。我如何完成 task.also 需要知道如何使我的网站 api 仅响应从我的网站发出的 cors 请求以及我的网站 api 如何响应网站的 C# 请求来自我的网站?

您可以限制令牌、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);
    }
}

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