Spring REST Api -- access User details in repository

Viewed 1154

The setup of the RESPApi project is:

  • SpringBoot
  • Spring's OAuth2

In the project we have many clients, so SQL queries almost always have "... and clientId = ?" in the where clause.

We store clientId in the SecurityContext with other user details (we extend Spring's User class).

The question is: how to get the User object in the @Repository?

Possible solutions we can think of:

  1. In every repository implementation add

SecurityContextHolder.getContext().getAuthentication()

cast the result to our custom UserDetails implementation and use it.

Cons: somehow I feel there's a better solution.

  1. Add @AuthenticationPrincipal annotated parameters to the controllers and then pass the parameters to the service layer and then to the repository layer.

Cons: passing the paremeter though 2 layers only to obtain clientId doesn't seem reasonable.

I thought about @Autowired paramter MyUser user in the @Repository class. The first try was to create @Configuration annotated class in which there will be a method

    @Bean
public MyUser getUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context != null) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return (MyUser) authentication.getPrincipal();
        }
    }
    return null;
}

But the bean is null and I cannot use it.

For now we've ended up with solution nr 1 but I feel there must be a better way.

Any ideas how to solve this problem?

2 Answers
Related