我正在尝试通过自定义AuthenticationEntryPoint
为匿名未经授权的请求发送自定义错误public class AccessDeniedAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Autowired
private Messages messages;
@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException {
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON);
response.setCharacterEncoding("UTF-8");
final ObjectMapper mapper = new ObjectMapper();
final ApplicationErrorResponse error = new ApplicationErrorResponse(
Message.PERMISSION_FAILED.toString(),
messages.get(Message.PERMISSION_FAILED.toString()));
if (response.getWriter() != null) {
response.getWriter().write(mapper.writeValueAsString(error));
response.getWriter().flush();
}
}
Messages bean封装了默认的MessageSource(messages.properties),并通过MessageSourceAccessor返回值
@Component
public class Messages {
@Autowired
private MessageSource messageSource;
private MessageSourceAccessor accessor;
@PostConstruct
private void init() {
accessor = new MessageSourceAccessor(messageSource);
}
public String get(String code) {
return accessor.getMessage(code);
}
}
但是,当引发AccessDendiedException并调用AccessDeniedAuthenticationEntryPoint中的commence
方法时,注入/自动装配的Messages对象为null
。
我无法让Spring在自定义身份验证入口点中成功注入消息。
我甚至尝试注册MessageSource类型的bean
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
并尝试在AuthenticationEntryPoint中自动装配它,但它也没有用。
如何在自定义AuthenticationEntryPoint中成功注入/自动装配MessageSource?