问题描述
我正在尝试记录修改实体的用户.反向代理在请求标头中设置用户名.
I am trying to log the user that modified the entity. The reverse proxy is setting the user name in the request header.
当使用Rest Panache公开JAX-RS CRUD时,如何从独立的类中读取请求和标头
How can the request and headers be read from an independent class when rest Panache is used to expose JAX-RS CRUD
下面是我尝试过的示例,但我得到的是null或null指针是错误提示
below an example of what I tried but I am getting null or null pointer exep
package org.acme.manrest;
import javax.enterprise.context.RequestScoped;
import javax.persistence.PrePersist;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import org.acme.jpa.TBusiness;
import org.jboss.logging.Logger;
@RequestScoped
public class HeaderValue {
private static final Logger LOG = Logger.getLogger(HeaderValue.class);
@Context
HttpServletRequest request;
public HttpServletRequest getRequest() {
return request;
}
@Context
HttpHeaders httpHeaders;
@HeaderParam("x-remote-user")
String userName;
public String getUserName() {
LOG.info("xxx: " + getRequest().getHeader("x-remote-user"));
LOG.info("userName: " + userName);
LOG.info("getUserName2: " + getUserName2());
LOG.info("getUserName3: " + getUserName3());
return userName;
}
public String getUserName2() {
return httpHeaders.getRequestHeader("x-remote-user").get(0);
}
public String getUserName3() {
LOG.info("getUserName from class " + request.getHeader("x-remote-user"));
return request.getHeader("x-remote-user");
}
@PrePersist
void onPrePersist(TBusiness myEntity) {
LOG.info("getUserName: " + userName);
myEntity.createdBy = userName;
myEntity.updatedBy = userName;
}
}
是否可以在Quarkus中切换到JWT并使用JWT RBAC?
Could switching to JWT and using JWT RBAC in Quarkus be a workaround?
推荐答案
通过添加underwow依赖关系使此功能起作用:
got this to work by adding undertow dependency :
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-undertow</artifactId>
</dependency>
然后在 PrePersist
方法下面创建的 EntityListener
类中:
then in an EntityListener
class created below PrePersist
method:
@RequestScoped
// @Path("api/v1/Header")
public class AuditingEntityListener {
private static final Logger LOG = Logger.getLogger(AuditingEntityListener.class);
// Inject the bean so that Quarkus does not remove it at build time (IMPORTANT)
@Inject
HttpServletRequest requestNotUsed;
@PrePersist
void onPrePersist(TBusiness myEntity) {
HttpServletRequest HSR = CDI.current().select(HttpServletRequest.class).get();
LOG.info("HSR getRequestHeader user: " + HSR.getHeader("x-remote-user"));
}
}
在Quarkus中使用JWT RBAC也可以:
using JWT RBAC in Quarkus also works:
@PrePersist
void onPrePersist(TBusiness myEntity) {
JsonWebToken context = CDI.current().select(JsonWebToken.class).get();
LOG.info("context: " + context.getClaim("preferred_username"));
}
这篇关于使用Quarkus休息数据时,Panache如何从@PrePersist中的请求标头访问用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!