我正在编写一个 Google Chrome 扩展程序,它需要我使用 Spring 设置的用户身份验证,目前我的代码中有几个示例用户名和密码,而我仍在开发中。此时,我已准备好添加真实的用户名和密码,但我希望能够将它们从外部文件加载到 AuthenticationManagerBuilder
对象中。
目前相关代码如下:
@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");
}
我希望能够构建 auth
对象,而不是从包含如下内容的文件:
user1 password1
user2 password2
user3 password3
我该怎么做(如果可能的话)?
最佳答案
使用 UserDetailsService
反而。只需读取 loadUserByUsername(String username)
方法中的文件,如果存在具有给定 username
的任何用户,则返回 UserDetails
或 User
代表那个用户。否则抛出 UsernameNotFoundException
异常:
@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");
}
});
}
关于java - 如何从文件将用户添加到 AuthenticationManagerBuilder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37972845/