简体   繁体   English

将Authorization标头中的api密钥发送到REST Web API

[英]Sending api key in Authorization header to a REST Web API

I have a REST Web API which receives some apiKey . 我有一个REST Web API,可以接收一些apiKey An example of a GET action of this Web API is: 此Web API的GET操作的示例是:

public HttpResponseMessage Get(int id, string apiKey)

The only route that is defined in my Web API is: 我的Web API中定义的唯一路由是:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Now, there is a web client that uses this Web API and it sends the apiKey in the query string when doing GET requests. 现在,有一个使用此Web API的Web客户端,当执行GET请求时, apiKey在查询字符串中发送apiKey

I understand that it is better to send the apiKey in the Authorization header of the request. 我知道最好在请求的Authorization标头中发送apiKey

Can someone show me how can I do a GET request and put that apiKey in the Authorization header and still land in the corect action method (I mean here the Get method above)? 有人可以告诉我如何执行GET请求并将该apiKey放在Authorization标头中,然后仍然位于corect动作方法中(我的意思是上面的Get方法)?

You can trick web api into thinking the Authorization header is parameter that came from the query string with a small message handler. 您可以诱使Web api认为Authorization标头是来自带有小消息处理程序的查询字符串的参数。

 public class ApiKeyHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var routeData = request.GetRouteData();

            if (request.Headers.Authorization != null && !routeData.Values.ContainsKey("apikey"))
            {
                routeData.Values.Add("apikey",request.Headers.Authorization.Parameter);
            }
            return base.SendAsync(request, cancellationToken);
        }
    }

This handler will grab the route data that has been extracted from the URI and if you pass an authorization header, it will take the parameter value and set it to be an apikey route parameter. 该处理程序将获取已从URI中提取的路由数据,如果传递了授权标头,它将获取参数值并将其设置为apikey路由参数。

The authorization header needs to look something like 授权标头应类似于

Authorization: apikey 12323434234234234

You can install the message handler by adding this link into your WebApiConfig.Register method. 您可以通过将此链接添加到WebApiConfig.Register方法中来安装消息处理程序。

config.MessageHandlers.Add(new ApiKeyHandler());

As an aside, you can use a handler like this to actually validate the ApiKey. 顺便说一句,您可以使用类似这样的处理程序来实际验证ApiKey。 This way you don't actually need to pass the apikey to your action method. 这样,您实际上不需要将apikey传递给您的操作方法。 Simply return a 401 directly from your handler if the ApiKey is no good. 如果ApiKey不好,只需直接从处理程序中返回401。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM