Passing parameters in the message header with a RE

2020-02-11 02:44发布

问题:

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).

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-". The behavior of this parameter is exactly the same than Path or Query params ?

I'm using Jersey.

Thank you for you help.

回答1:

  1. Yes I believe it is acceptable to have header parameters to transfer certain data. The JAX-RS standard even defines the @HeaderParam annotation. Simple example of @HeaderParam.

  2. It is a convention to prefix non-standard http headers with "x-".

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;
    }
}