我目前的代码是
@Path("login")
@RequestScoped
public class LoginResource {
@GET
@SecurityChecked
public Response getUser(@HeaderParam("AUTH") @Nonnull final String authToken) {
return Response.ok("authenticated successfully.").build();
}
}
和@SecurityChecked
是自定义注释
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@Inherited
@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SecurityChecked {
}
和Interceptor类为
@Interceptor
@SecurityChecked
public class SecurityCheckInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger("SecurityCheckInterceptor");
@AroundInvoke
public Object validateUser(final InvocationContext context) throws Exception {
final Object[] params = context.getParameters();
LOGGER.info("Authentication token: " + Arrays.toString(params));
return context.proceed();
}
}
当我运行它时,我看到了
Authentication token: [1a629d035831feadOO4uFReLyEW8aTmrCS]
问题吗
- 在我的资源类中,我必须传递@HeaderParam
参数
- 如何阅读来自客户端的所有HTTP
标题?
理想吗
- 如果getUser()
未接受任何@HeaderParam
输入,则
- 拦截器应该能够为你提供所有HTTP
标题
我该怎么做?
答案 0 :(得分:5)
我通过修改我拥有的拦截器来解决这个问题,以下是代码
<强>注释强>
@Inherited
@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface SecurityChecked {
}
资源类
public class SecureResource {
@GET
@SecurityChecked
public Response getUser() {
return Response.ok("authenticated successfully!").build();
}
}
拦截器类
@Interceptor
@Provider
@ServerInterceptor
@SecurityChecked
public class SecurityCheckInterceptor implements PreProcessInterceptor, AcceptedByMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(SecurityCheckInterceptor.class);
@Nullable
@Override
public ServerResponse preProcess(final HttpRequest request, final ResourceMethod method) throws Failure, WebApplicationException {
final List<String> authToken = request.getHttpHeaders().getRequestHeader("X-AUTH");
if (authToken == null || !isValidToken(authToken.get(0))) {
final ServerResponse serverResponse = new ServerResponse();
serverResponse.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return serverResponse;
}
return null;
}
private static boolean isValidToken(@Nonnull final String authToken) {
LOGGER.info("validating token: " + authToken);
return true;
}
@SuppressWarnings("rawtypes")
@Override
public boolean accept(final Class declaring, final Method method) {
// return declaring.isAnnotationPresent(SecurityChecked.class); // if annotation on class
return method.isAnnotationPresent(SecurityChecked.class);
}
}
然后我通过在JBoss中部署资源类并在命令行上发出以下命令来运行我的集成测试
curl --header 'X-AUTH: 1a629d035831feadOOO4uFReLyEW8aTmrCS' http://localhost:8080/market-1.0-SNAPSHOT/rest/login
curl --header 'InvalidHeader: InvalidHeaderValue' http://localhost:8080/market-1.0-SNAPSHOT/rest/login