在Spring Security中将属性文件与Java配置一起用于用户凭证

时间:2019-01-10 20:07:35

标签: spring-security

在XML配置中,可以引用定义用户凭据的属性文件。例如:

<security:user-service id="userDetailsService" properties="classpath:users.properties"/>

但是,在Java配置中,没有可用的默认替代方法(据我所知),而是编写了自己的实现,如:

@Bean
public UserDetailsService userDetailsService() {
    Properties properties = new Properties();
    try {
        File file = ResourceUtils.getFile("classpath:users.properties");
        properties.load(new FileInputStream(file));

        return new InMemoryUserDetailsManager(properties);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

我想知道Spring Security框架提供的开箱即用的功能是否会很好。像这样:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication("classpath:user.properties")
    ...

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUserCredentialsFile("classpath:user.properties")
    ...

1 个答案:

答案 0 :(得分:1)

我不确定在Spring Security中添加此改进是否有意义。如您所概述,等效的Java配置为:

@Bean
public UserDetailsService userDetailsService() throws Exception {
    Properties users = PropertiesLoaderUtils.loadAllProperties("users.properties");
    return new InMemoryUserDetailsManager(users);
}

对于用户来说,这看起来很简单。你觉得呢?