【发布时间】:2019-05-24 10:41:50
【问题描述】:
我的目标是为服务器上的单个资源提供身份验证,为此我使用自定义过滤器。由于使用 JAVA 1.6 的限制,我没有使用@NameBinding。使用Response.header(HttpHeaders.WWW_AUTHENTICATE,"Basic") 不会提示输入凭据。
使用 ContainerRequestFilter 对我的事业没有帮助,因为它会对服务器的每个资源进行过滤。
过滤器
@Provider
public class AuthenticationFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
System.out.println("Entered authentication filter");
throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.AUTHORIZATION,"Basic")
.entity("Credentials are required to access this resource.")
.build());
// chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void destroy() {}
}
web.xml 映射
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>Utils.LDAPAuthentication.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/download</url-pattern>
</filter-mapping>
【问题讨论】:
-
你不能在 servlet 过滤器中做“JAX-RS 的东西”。如果您打算使用 servlet 过滤器,那么您需要坚持简单地使用 servlet API。只需在 HttpServletResponse 上设置标头即可。
-
它没有提示,即使在为 HttpServletResponse 设置标头之后也是如此。
-
你在设置什么标题?
-
我明白了,通过将标头设置为 WWW_AUTHENTICATE。
标签: jax-rs jax-ws basic-authentication