I am writing a Google Chrome extension that requires user authentication that I have set up with Spring, and currently I have a few example usernames and passwords in my code while I'm still developing. At this point, I am ready to add real usernames and passwords, but I want to be able to load them into an AuthenticationManagerBuilder object from an outside file.
Here is the relevant code so far:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1").password("password1").roles("USER").and()
.withUser("user2").password("password2").roles("USER").and()
.withUser("user3").password("password3").roles("USER");
}
I want to be able to build the auth object instead from a file that would contain something like this:
user1 password1
user2 password2
user3 password3
How would I do this (if it is even possible)?
Use a UserDetailsService instead. Just read the file inside the loadUserByUsername(String username) method, if any user with the given username exists, return a UserDetails or User representing that user. Otherwise throw a UsernameNotFoundException exception:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// Read the file
// Loop through all users and search for the given username
// Return User or throw UsernameNotFoundException
auth.userDetailsService(username -> {
try {
String pathToFile = // Path to file;
List<String> users = Files.readAllLines(Paths.get(pathToFile));
for (String user : users) {
String[] parts = user.split("\\s+", 2);
String theUsername = parts[0];
String password = parts[1];
if (username.equals(theUsername))
return new User(theUsername, password, Collections.singleton(new SimpleGrantedAuthority("USER")));
}
throw new UsernameNotFoundException("Invalid username");
} catch (Exception e) {
throw new UsernameNotFoundException("Invalid username");
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With