Spring security onAuthenticationSuccess java配置,存储库访问->;无效的
我正在使用spring4和SpringSecurity、SpringDataJPA和SpringBoot。成功进行用户身份验证后,我需要进行一些处理(例如,将一些数据保存到会话中)。所以我的代码是:Spring security onAuthenticationSuccess java配置,存储库访问->;无效的,spring,hibernate,spring-mvc,spring-security,Spring,Hibernate,Spring Mvc,Spring Security,我正在使用spring4和SpringSecurity、SpringDataJPA和SpringBoot。成功进行用户身份验证后,我需要进行一些处理(例如,将一些数据保存到会话中)。所以我的代码是: @Component public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { @Autowired UserRepository userRepository;
@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:null位于org.pckg.MyAuthenticationSuccessHandler.onAuthenticationSuccess(MyAuthenticationSuccessHandler.java:40)
当我在其他地方调用这个userService.findBySomething()例如controller时,调用就成功了。为什么不在spring security完成身份验证过程并将用户重定向到主页之后,在主视图控制器中添加属性呢
编辑:在用户存储库中显示代码自动连接,但在访问用户服务的代码中显示代码自动连接。假设您正在显示所有代码,您还需要在userService对象中自动连线。好的,我解决了这个问题。而不是
http.formLogin().successHandler(new MyAuthenticationSuccessHandler())
通过依赖项注入注入authenticationsuccesshandler:
@Autowired MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
http.formLogin().successHandler(myAuthenticationSuccessHandler);
它是JSON rest后端,可以访问不同的url,没有类似于“主url”的东西。我认为在不同的框架中成功登录后,将这种类型的数据放在适当的位置是很常见的,但在SpringSecurity中这样做看起来确实很痛苦。