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

Java 如何将用户从文件添加到AuthenticationManagerBuilder?,java,spring,spring-security,Java,Spring,Spring Security,我正在编写一个GoogleChrome扩展,它需要使用Spring设置的用户身份验证,目前我在代码中有一些用户名和密码示例,而我还在开发中。现在,我已经准备好添加真实的用户名和密码,但我希望能够从外部文件将它们加载到AuthenticationManagerBuilder对象中 以下是迄今为止的相关代码: @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

我正在编写一个GoogleChrome扩展,它需要使用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
我该怎么做(如果可能的话)?

使用a代替。只要读取
loadUserByUsername(stringusername)
方法中的文件,如果存在具有给定
username
的任何用户,请返回或表示该用户。否则将引发异常:

@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");
            }
    });
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)引发异常{
//读文件
//遍历所有用户并搜索给定的用户名
//返回用户或抛出UsernameNotFoundException
auth.userDetailsService(用户名->{
试一试{
String pathToFile=//文件的路径;
List users=Files.readAllLines(path.get(pathToFile));
for(字符串用户:用户){
String[]parts=user.split(“\\s+”,2);
字符串theUsername=parts[0];
字符串密码=部件[1];
if(username.equals(theUsername))
返回新用户(用户名、密码、Collections.singleton(新的SimpleGrantedAuthority(“用户”));
}
抛出新用户名NotFoundException(“无效用户名”);
}捕获(例外e){
抛出新用户名NotFoundException(“无效用户名”);
}
});
}
我找到了一个更简单的方法:

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        InMemoryUserDetailsManagerConfigurer imudmc = auth.inMemoryAuthentication();
        String[] creds = {"user|password", "user2|password"};
        for (int i = 0; i < creds.length; i++) {
            imudmc.withUser(StringUtils.substringBefore(creds[i], "|")).password(StringUtils.substringAfter(creds[i], "|")).roles("USER");
        }
    }
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)引发异常{
InMemoryUserDetailsManager配置器imudmc=auth.inMemoryAuthentication();
字符串[]creds={“用户|密码”,“用户2 |密码”};
对于(int i=0;i

显然,数组应该从文件中读入。

在JSON中定义,包括角色。使用自己的serialiser(支持JSON和XML)从字符串文件测试


您是否可以进一步扩展此代码?谢谢@ali dehghanigiven在
split
电话中,我的用户/密码文件有什么特殊的格式吗?如中所示,用户空间密码或用户选项卡密码?
\\s+
表示至少一个
空间
,它涵盖了上述两种情况
        consumers = (Consumers) serialiser.recover("{ \"Consumers\" : [ { \"Name\" : \"localhost\", \"Password\" : \"none\", \"Roles\" : [ \"USER\", \"ADMIN\" ]  } ]}", Consumers.class);
        if (null != consumers && null != consumers.getConsumers()) {
            InMemoryUserDetailsManagerConfigurer imudmc = auth.inMemoryAuthentication();
            for (Consumer consumer : consumers.getConsumers()) {
                   imudmc.withUser(consumer.getName()).password(consumer.getPassword()).roles(consumer.getRoles());
            }
        }