简体   繁体   English

使用REST API传递消息头中的参数

[英]Passing parameters in the message header with a REST API

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). 我正在开发一个REST API,我需要传输密码来为应用程序中的每个请求验证消息(来自密钥的MAC加密)。 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). 我正在考虑将它们放在消息头中,以避免在包含发布/检索对象(XML或JSON)的消息体中添加非数据信息。

Is it a best practise ? 这是最佳做法吗?

Can I add as many parameters I want in the header ? 我可以在标题中添加所需的参数吗? I've read that I must prefix them with "x-". 我读过我必须用“x-”作为前缀。 The behavior of this parameter is exactly the same than Path or Query params ? 此参数的行为与Path或Query参数完全相同?

I'm using Jersey. 我正在使用泽西岛。

Thank you for you help. 谢谢你的帮助。

  1. Yes I believe it is acceptable to have header parameters to transfer certain data. 是的我认为有标头参数来传输某些数据是可以接受的。 The JAX-RS standard even defines the @HeaderParam annotation . JAX-RS标准甚至定义了@HeaderParam注释 Simple example of @HeaderParam . @HeaderParam的简单示例

  2. It is a convention to prefix non-standard http headers with "x-". 将非标准http标头作为“x-”加上前缀是一种惯例。

I had a similar situation to yours: I needed to transfer user token and application ID with every REST call. 我遇到了类似的情况:我需要在每次REST调用时传输用户令牌和应用程序ID。 To avoid code duplication I implemented PreProcessInterceptor (I'm using Resteasy), through which all REST requests are routed. 为了避免代码重复,我实现了PreProcessInterceptor (我正在使用Resteasy),通过它来路由所有REST请求。 If user token is not valid and if user does not have privileges to given application ID, then I return 401 unauthorized. 如果用户令牌无效且用户没有给定应用程序ID的权限,那么我将返回401未授权。 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;
    }
}

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

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