使用REST API传递消息头中的参数 [英] Passing parameters in the message header with a REST API
问题描述
我正在开发一个REST API,我需要传输密码来为应用程序中的每个请求验证消息(来自密钥的MAC加密)。我正在考虑将它们放在消息头中,以避免在包含发布/检索对象(XML或JSON)的消息体中添加非数据信息。
I'm developping a REST API and I need to tranport cryptograms to authenticate the message for each request in a applicative process (MAC encryption from secret keys). I was thinking about putting them in the message header to avoid adding non-data information in the message body which contains the posted/retrieved object (XML or JSON).
是这是最佳做法?
我可以在标题中添加任意数量的参数吗?我读过我必须用x-作为前缀。此参数的行为与Path或Query参数完全相同?
Can I add as many parameters I want in the header ? I've read that I must prefix them with "x-". The behavior of this parameter is exactly the same than Path or Query params ?
我正在使用Jersey。
I'm using Jersey.
谢谢你的帮助。
推荐答案
-
是的我认为有标头参数来传输某些数据是可以接受的。 JAX-RS标准甚至定义了 @HeaderParam注释 。简单的 @HeaderParam的例子。
将非标准http标头加上x - 前缀是一种约定。
It is a convention to prefix non-standard http headers with "x-".
我遇到了类似的情况:我需要在每次REST调用时传输用户令牌和应用程序ID。为了避免代码重复,我实现了 PreProcessInterceptor
(我正在使用Resteasy),通过它来路由所有REST请求。如果用户令牌无效且用户没有给定应用程序ID的权限,那么我将返回401未授权。我的代码与此类似(简化版):
I had a similar situation to yours: I needed to transfer user token and application ID with every REST call. To avoid code duplication I implemented PreProcessInterceptor
(I'm using Resteasy), through which all REST requests are routed. If user token is not valid and if user does not have privileges to given application ID, then I return 401 unauthorized. My code looked similar to this (simplified version):
@Provider
@ServerInterceptor
public class RestSecurityInterceptor implements PreProcessInterceptor {
@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws UnauthorizedException {
String token = request.getHttpHeaders().getRequestHeader("token").get(0);
// user not logged-in?
if (checkLoggedIn(token)) {
ServerResponse response = new ServerResponse();
response.setStatus(HttpResponseCodes.SC_UNAUTHORIZED);
MultivaluedMap<String, Object> headers = new Headers<Object>();
headers.add("Content-Type", "text/plain");
response.setMetadata(headers);
response.setEntity("Error 401 Unauthorized: "
+ request.getPreprocessedPath());
return response;
}
return null;
}
}
这篇关于使用REST API传递消息头中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!