java - 如何从文件将用户添加到 AuthenticationManagerBuilder?

标签 java spring spring-security

我正在编写一个 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 的任何用户,则返回 UserDetailsUser代表那个用户。否则抛出 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/

相关文章:

java - Maven 3.3.1 ECLIPSE : -Dmaven. multiModuleProjectDirectory 系统属性未设置

java - 显示西里尔字母的 libgdx

java - 由于 org.springframework.core.ResolvableTypeProvider,上下文初始化失败

java - STS 全部构建按钮呈灰色

java - 嵌入式 Jetty 环境中的 Spring Boot 和 Spring Security 集成

java - Java soap 中的 UserNameToken

java - 禁用选择 jTextfield 的所有突出显示

java - DBUnit 和 Spring Boot - 在集成测试中请求时可能无法导入或不存在数据

java - 我可以将 3 种不同的身份验证方案放在同一个 spring 安全配置中吗?

java - Spring 为未定义的 bean 抛出异常