Java 使用GUI在RESTEasy中将主体注入资源方法
我正在使用RESTEasy和Guice开发一个RESTAPI,目前我正试图通过使用类似于Dropwizard中的@Auth的注释来合并基本身份验证。与Java 使用GUI在RESTEasy中将主体注入资源方法,java,rest,guice,code-injection,resteasy,Java,Rest,Guice,Code Injection,Resteasy,我正在使用RESTEasy和Guice开发一个RESTAPI,目前我正试图通过使用类似于Dropwizard中的@Auth的注释来合并基本身份验证。与 @Path("hello") public class HelloResource { @GET @Produces("application/json") public String hello(@Auth final Principal principal) { return principal.get
@Path("hello")
public class HelloResource {
@GET
@Produces("application/json")
public String hello(@Auth final Principal principal) {
return principal.getUsername();
}
}
hello资源调用应该被一些代码截获,这些代码使用在Authorization HTTP请求头中传递的凭据执行基本身份验证,并在成功地将主体注入到method principal参数中时执行基本身份验证。我还希望能够将允许的角色列表传递给注释,例如@Auth(“admin”)
我真的需要一些关于如何实现这一目标的建议?我认为您最好的选择是在请求范围内使用中间值。假设您没有将
HelloResource
放在singleton作用域中,您可以将这个中间值注入一些ContainerRequestFilter
实现和您的资源中,您可以在ContainerRequestFilter
实现中填充所需的所有身份验证和授权信息
它看起来像这样:
// Authentication filter contains code which performs authentication
// and possibly authorization based on the request
@Provider
public class AuthFilter implements ContainerRequestFilter {
private final AuthInfo authInfo;
@Inject
AuthFilter(AuthInfo authInfo) {
this.authInfo = authInfo;
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// You can check request contents here and even abort the request completely
// Fill authInfo with the data you need
Principal principal = ...; // Ask some other service possibly
authInfo.setPrincipal(principal);
}
}
@Path("hello")
public class HelloResource {
private final AuthInfo authInfo;
@Inject
HelloResource(AuthInfo authInfo) {
this.authInfo = authInfo;
}
@GET
@Produces("application/json")
public String hello() {
// authInfo here will be pre-filled with the principal, assuming
// you didn't abort the request in the filter
return authInfo.getPrincipal().getUsername();
}
}
public class MainModule extends AbstractModule {
@Override
protected void configure() {
bind(AuthFilter.class);
bind(HelloResource.class);
bind(AuthInfo.class).in(RequestScoped.class);
}
}
即使您出于某种原因将资源(甚至过滤器)放入了singleton范围,您也可以随时插入
提供者。谢谢!希望有一种更直接地将主体注入资源方法的方法,但我想我不得不放弃这个想法;)当我尝试您的代码时,在执行我的资源方法时,身份验证信息的主体尚未设置。想知道我错过了什么…我想我应该提出一个新问题,关于我在限定身份验证信息请求范围方面遇到的问题?@Stine,请查看我的更新)你比我快了二分之一:)