0

I'm new to spring, and i'm trying to create my own user and authenticate it. So far everything works, i can login and logout, but i can't autowire my userrepository in the authentication success/failure handler. I can do it everywhere else, for example in a controller.

My handler looks like this:

@Service
public class MyAuthenticationSuccessHandler extends 
SavedRequestAwareAuthenticationSuccessHandler {

@Autowired
UserRepository userRepository;

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
    [...]
    User user = (User)authentication.getPrincipal();
    user.setLastLogin(now);
    userRepository.save(user);
    [...]
}
}

when i'm trying to save the user, i get a nullpointer exception, because the userrepository is null.

The userrepository looks like this:

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByName(String name);
}

However i can autowire it everywhere else the same way i'm trying in the sucesshandler. For example in a controller.

Could someone tell me what am i doing wrong?

iron24
  • 101
  • 1
  • 4
  • 19
  • I forgot to mention my success handler is in the config package, and my repository is in the app package, the package structure look like this: app: Application.java(the main) + Repository config: My authentication handlers and stuff. In the ComponentScan and EnableJpaRepositories annotation i'm using the "basePackages = {"config", "app"}". I tried to move the config inside the app package, but that did not help either. – iron24 Aug 02 '18 at 08:06
  • Let me guess inside the configure method of Spring Security you do `new MyAuthenticationSuccessHandler()`... Instead of having created an `@Bean` annotated method for it. – M. Deinum Aug 02 '18 at 08:07
  • You are right, but how do i do that with a bean? – iron24 Aug 02 '18 at 08:09
  • Just create an `@Bean` method for the handler and reference that in your other `@Bean` method. – M. Deinum Aug 02 '18 at 08:12
  • Thank you so much! – iron24 Aug 02 '18 at 08:16

2 Answers2

2

When I use such class I annotate it with @Component instead of @Service (esthetics).

If you get a NPE at that point it's because MyAuthenticationSuccessHandler is not being managed. You have either scan the package or @Bean it at a Configuration class.

Juan Diego
  • 863
  • 1
  • 10
  • 22
1

Are you scanning the package that contains your handler? It seems like you put @Service annotation but if you don't scan the package it will be useless because spring wouldnt know about it.

kozgurd
  • 61
  • 1
  • 6