从AuthenticationSuccessHandler获取映射器

时间:2016-02-03 21:05:18

标签: spring-security spring-boot jackson jersey-2.0

我试图在Spring Boot应用程序中成功登录后返回一些用户数据。 为此,我需要使用已在工厂通过bootstrap设置的Jackson映射器序列化我的Principal。

有没有办法将它注入认证处理程序?

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    response.setStatus(HttpServletResponse.SC_OK);
    UserDetails me = (UserDetails) authentication.getPrincipal();
    PrintWriter writer = response.getWriter();
    /*mapper.writeValue(writer, user); <- how to get the mapper?
    writer.flush();*/
}

1 个答案:

答案 0 :(得分:0)

TL;博士;

不要使用Factory,而是将ObjectMapper设为Spring bean。这样就可以将它注入到Spring Jersey组件中。

@Bean
public ObjectMapper mapper() {
    ObjectMapper mapper = new ObjectMapper();
    return mapper;
}

当您使用HK2(泽西岛的DI框架)Factory创建ObjectMapper时,注入仅适用于通过HK2 ServiceLocator检索的组件,这是Spring ApplicationContext的HK2类似物。

当你使用带有泽西岛的Spring-Boot时,两者如何在引擎盖下相互作用,是通过HK2 spring-bridge。例如,假设AuthenticationSuccessHandler已在ApplicationContext中注册。配置弹簧桥后,我们还可以通过AuthenticationSuccessHandler

获取ServiceLocator
ServiceLocator l = ...
AuthenticationSuccessHandler handler = l.getService(AuthenticationSuccessHandler.class);

那应该有用。如果您通过HK2 ObjectMapper绑定了Factory,并且您将@Inject映射到了AuthenticationSuccessHandler,那么当通过{{1}检索时,它会被注入}}

话虽如此,Spring Security并没有通过HK2,所以它永远没有机会通过HK2获得ServiceLocator。但是如果你将mapper注册为Spring bean,那么Spring可以将它注入ObjectMapper。并且映射器仍然可以通过HK2 AuthenticationSuccessHandler(因为弹簧桥),因此您仍然可以将它与泽西一起使用,就像它与ServiceLocator绑定一样。

相关问题