我有一个 Jersey 2 应用程序,其中包含消耗和生成 json 的资源。我的要求是向由各种响应数据组合生成的授权响应 header 添加签名(类似于 Amazon Webservices 请求签名)。这些数据之一是响应正文,但我看不到有任何过滤器或拦截点允许我访问 json 内容。我想这主要是因为响应输出流是用于写入而不是读取。
关于如何阅读响应正文或替代方法有什么想法吗?
谢谢。
最佳答案
我的理解是,当您的应用程序响应请求时,您希望通过向其值添加签名来修改 Authorization
header 。
如果是这种情况,您需要实现一个 ContainerResponseFilter
:
public class MyContainerResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
// You can get the body of the response from the ContainerResponseContext
Object entity = containerResponseContext.getEntity();
// You'll need to know what kind of Object the entity is in order to do something useful though
// You can get some data using these functions
Class<?> entityClass = containerResponseContext.getEntityClass();
Type entityType = containerResponseContext.getEntityType();
// And/or by looking at the ContainerRequestContext and knowing what the response entity will be
String method = containerRequestContext.getMethod();
UriInfo uriInfo = containerRequestContext.getUriInfo();
// Then you can modify your Authorization header in some way
String authorizationHeaderValue = containerResponseContext.getHeaderString(HttpHeaders.AUTHORIZATION);
authorizationHeaderValue = authorizationHeaderValue + " a signature you calculated";
containerResponseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, authorizationHeaderValue);
}
}
请注意,即使 Jersey 找不到请求路径的匹配资源,也会对应用程序的所有请求调用 filter
函数,因此您可能需要进行一些额外的检查.
关于java - 与 Jersey 的响应授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996562/