【问题标题】:Spring security onAuthenticationSuccess java config , repository access-> nullSpring security onAuthenticationSuccess java config,存储库访问-> null
【发布时间】:2014-03-21 00:23:25
【问题描述】:

我正在使用 spring4 和 spring security、spring data jpa、spring boot。成功用户身份验证后,我需要进行一些处理(例如,将一些数据保存到会话中)。所以我的代码:

@Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired UserRepository userRepository;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        request.getSession().setAttribute("attribute1",userService.findBySomething() );
        super.onAuthenticationSuccess(request, response, authentication);
    }
}


@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
            http.formLogin().successHandler(new MyAuthenticationSuccessHandler())
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
   }

//another methods ..
}

调用 userService.findBySomething() 后: java.lang.NullPointerException:在 org.pckg.MyAuthenticationSuccessHandler.onAuthenticationSuccess 处为空(MyAuthenticationSuccessHandler.java:40) 当我在其他地方(例如控制器)调用此 userService.findBySomething() 时,调用成功。

【问题讨论】:

    标签: spring hibernate spring-mvc spring-security


    【解决方案1】:

    好的,我解决了这个问题。而不是

        http.formLogin().successHandler(new MyAuthenticationSuccessHandler())
    

    通过依赖注入注入authenticationsuccesshandler:

        @Autowired MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    
        http.formLogin().successHandler(myAuthenticationSuccessHandler);
    

    【讨论】:

      【解决方案2】:

      为什么不在 Spring Security 完成身份验证过程并将用户重定向到您的主页后,在主视图控制器中添加属性?

      编辑:您在用户存储库中显示代码自动装配,但在您访问用户服务的代码中。假设您要显示所有代码,您还需要在 userService 对象中自动装配。

      【讨论】:

      • 它是 JSON rest 后端,可以访问不同的 url,没有“home url”之类的东西。我认为在不同框架中成功登录后将此类数据放置到位是很常见的,但在 Spring Security 中这样做看起来真的很痛苦。
      猜你喜欢
      • 2017-06-20
      • 2017-05-22
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多