Authentication 将用户信息传播到Dropwizard中的所有层

Authentication 将用户信息传播到Dropwizard中的所有层,authentication,dropwizard,Authentication,Dropwizard,我在Dropwizard应用程序中使用基本身份验证机制,在其中捕获登录的用户详细信息,如下所示: @POST @Timed @Consumes(MediaType.APPLICATION_JSON) @Produces("application/pdf") @Path("/") @RolesAllowed("user,admin") public Response function(@Auth User user) throws Exception { //some logic arou

我在Dropwizard应用程序中使用基本身份验证机制,在其中捕获登录的用户详细信息,如下所示:

@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf")
@Path("/")
@RolesAllowed("user,admin")
public Response function(@Auth User user) throws Exception {
    //some logic around here
}
Thread.current[:user] = user
现在出于审计目的,我希望在我的应用程序的每一层传递这个用户信息,我的意思是在服务、DAO、ExceptionMappers等中,我不希望将它作为函数参数到处传递,因为它看起来很笨拙,而且还有可维护性开销。所以我的问题是,有没有任何方法可以让我们在每次REST调用或用户会话中设置一些全局配置,并可以在我想要的任何地方获取它? 我曾经是一名Ruby用户,在这方面我们可以做如下工作:

@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf")
@Path("/")
@RolesAllowed("user,admin")
public Response function(@Auth User user) throws Exception {
    //some logic around here
}
Thread.current[:user] = user

在每个用户会话中都可以访问它。

实现这一点的一种方法是使用Java,您可以在其中设置用户对象,并且它将可用于特定的执行器线程

将以下内容添加到资源类中

private static ThreadLocal<User> localUser = new InheritableThreadLocal<>();

public static ShortenerServiceUser getUser() {
    return localUser.get();
}
现在,每当您需要从当前线程上下文访问用户对象时,您只需执行以下操作

User localUser = YourResource.getUser();

您可以使用ThreadLocal.remove()方法从上下文中清除用户对象。

实现这一点的一种方法是使用Java,您可以在其中设置用户对象,并且它将可用于特定的执行器线程

将以下内容添加到资源类中

private static ThreadLocal<User> localUser = new InheritableThreadLocal<>();

public static ShortenerServiceUser getUser() {
    return localUser.get();
}
现在,每当您需要从当前线程上下文访问用户对象时,您只需执行以下操作

User localUser = YourResource.getUser();
可以使用ThreadLocal.remove()方法从上下文中清除用户对象