Spring Security in a Maven multi-module project (where to put DB auth, UserDetails, etc.?)

Currently we have 6 Maven modules:

  • webapp
  • security
  • core (provides database access for User )
  • common
  • module1
  • module2

The dependency tree is pretty obvious, I think:

  • webapp depends on everything
  • security depends on the kernel
  • core depends on the usual
  • common does not depend on anything
  • module1 depends on the main and general
  • module2 depends on the kernel, module 1 and the general

Now I would like to have several BaseEntity : it should have @PrePersist , which saves the current User . Almost every object will use this BaseEntity . Therefore, each module depends on core .

And since everything depends on core , it is logical to put this BaseEntity in the core module. (even if I prefer to use common for this, but this seems impossible due to dependencies).

Now the problem is: To set the current user, I have to use SecurityContextHolder.getContext().getAuthentication().getPrincipal() . But with that I would have some kind of unwanted addiction (or am I just nodding too much?).

The problem gets even worse if I want to have a custom implementation of UserDetails . Where should I put this? core or security ? Or is it usually simple to implement a User UserDetails object? I do not think so. The question is, because when authenticating a user, I have to create a UserDetails object inside the security module. And when I want to get the current User , I would have to apply the getPrincipal() method to the user class UserDetails .

I'm really confused about how to leave things loosely coupled, but also achieve everything I need for the application.

The last idea that occurred to me was to use Dependency Injection, but I don’t know if it works !? (Having a currentUser Bean inside the security module, and everyone else can just get it via @Autowired MyCustomUserDetails )

So please help me get it right!

Thanks! :)

+4
source share

Source: https://habr.com/ru/post/1493074/


All Articles