我使用jax-rs建立了休息api。要处理身份验证我使用Interceptor。当auth失败时,我返回WebApplicationException,如:
try
{
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(policy.getUserName(), policy.getPassword()));
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
}
catch (AuthenticationServiceException | BadCredentialsException e)
{
throw new WebApplicationException(Response.Status.UNAUTHORIZED); //TODO set response status
}
但它返回startus 500而不是401。
当我在服务中抛出WebApplicationExceptions时,它返回我设置的状态,但是在拦截器中它没有工作。如何从拦截器返回401?
jaxrs:服务器配置:
<jaxrs:server id="restService" address="/rest">
<jaxrs:serviceBeans>
<ref bean="serviceBean"/>
</jaxrs:serviceBeans>
<jaxrs:inInterceptors>
<ref bean="securityInterceptor"/>
</jaxrs:inInterceptors>
</jaxrs:server>
<bean id="serviceBean" class="some_package.CustomerService"/>
<bean id="securityInterceptor" class="some_package.AuthenticatorInterceptor"/>
答案 0 :(得分:1)
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
@Provider
public class Example implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
requestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
}
}
答案 1 :(得分:0)
在调用JAX-RS资源之前调用拦截器,这意味着它还不知道JAX-RS设置。
我会使用ExceptionMapper
转换为适当的响应,无论它从何处被抛出。