Reputation: 4609
I am building a SpringBoot application.
I am using Spring Security, and have a UserDetailsService implementation setup:
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User springUser = null;
User user = userService.loadUserByUsername(username);
if(user != null){
List<SimpleGrantedAuthority> authorities = null;
List<Role> roles = user.getRoles();
if(roles != null){
authorities = new ArrayList<>();
for(Role currentRole: roles){
authorities.add(new SimpleGrantedAuthority(currentRole.name()));
}
}
springUser = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
return springUser;
}
}
I have a service layer that contains method for adding users to the database:
public interface UserService {
public Long addStandardUser(String firstName, String lastName, String username, String password);
@PreAuthorize("hasRole('ADMIN')")
public Long addAdministratorUser(String firstName, String lastName, String username, String password);
@PreAuthorize("hasRole('ADMIN')")
public User loadUserByUsername(String username);
public Iterable<User> getUsers(int pageNumber, int pageSize, Direction direction, String sort);
}
I also have a CommandLineRunner implementation that I use (in dev mode) to initialize the database with sample users:
@Component
@Profile("dev")
public class DBInitializer implements CommandLineRunner {
@Autowired
private UserService userService;
@Override
public void run(String... args) throws Exception {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ADMIN"));
Authentication authentication = new UsernamePasswordAuthenticationToken("foo", null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
userService.addAdministratorUser("John", "Doe", "jdoe", "1234");
System.out.println("done!");
}
}
The trouble is that I am getting an Access Denied exception from Spring in the CommandLineRunner when I try to add the user. I'm assuming that the issue is that I am manually 'injecting' a Spring User incorrectly. The addAdminUser() method has to be run by a user in the ADMIN role, so I need to temporarily run as an ADMIN user. I know there is a @RunAs annotation that I remember using in other J2EE apps, but I'm not sure how that interfaces with a Spring application, or if that is used in a different context altogether
Upvotes: 5
Views: 6536