使用 REST API 在消息头中传递参数 [英] Passing parameters in the message header with a REST API

查看:16
本文介绍了使用 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 ?

我正在使用泽西岛.

感谢您的帮助.

推荐答案

  1. 是的,我认为使用标头参数来传输某些数据是可以接受的.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆