I inherited an app that controls access and editing of a small database. It uses Spring Security for auth. It uses a local table for users and roles.
The app provides an interface to create new users, if you have role ROLE_ADMIN. Inside the method for creating the user is a block of code like this:
Authentication authentication =SecurityContextHolder.getContext().getAuthentication();
accountService.createUser(getUserDetails(newUser,password,authentication),role,fullname, displayName);
I have to create new instances of this app with slightly configuration, and an empty database (except for static data). That means the user table is empty. I can only create new users if I can log in (the story about how they got the app running in the first place is confusing).
So, I defined a new bean with a @Component
annotation and a @PostConstruct
method which does this:
@PostConstruct
public void init() {
List<UserInfo> currentUserList = userAccountService.getCurrentUserList();
if (currentUserList.isEmpty()) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = new User("admin", "admin", true, true, true, true, authentication.getAuthorities());
userAccountService.createUser(user, EstimationConstants.ROLE_ADMIN, "admin", "admin");
}
}
When this runs, it gets a NPE because "authentication" is null. I imagine that's because it's not running as a logged-in user in the context.
How can I get this working?