在application.yml中定义基本安全性用户,密码和角色

时间:2016-10-06 12:29:40

标签: spring spring-security spring-boot spring-boot-actuator

我正在寻找一种使用Spring @Secured注释来保护方法的方法。对于大约10-15个用户,我不希望连接到数据库并从那里获取用户及其权限/角色,而是将它们本地存储在特定于配置文件的application.yml文件中。 Spring Boot中有一个概念支持这个想法吗?到目前为止我所能找到的只能使用基本的安全执行器('org.springframework.boot:spring-boot-starter-security'),看起来像这样:

security:
  basic:
    enabled: true
  user:
    name: admin
    password: admin
    role: EXAMPLE

但是,即使我认为用户 admin 不能访问所述方法,我仍然可以访问使用@RolesAllowed("READ")注释的方法。我的SecurityConfiguration看起来像这样:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
@Profile("secure")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .fullyAuthenticated()
                .and()
                .httpBasic();

        http.sessionManagement()
                .sessionFixation()
                .newSession();

        http.csrf().disable();
        http.headers().frameOptions().disable();

    }
}

最终这可能是一个不同的问题,但也许这对我自己的理解很重要。

我想知道如何在application.yml和注释方法中指定具有不同密码和不同角色的多个用户,以确保只有授权用户才能访问这些方法。

1 个答案:

答案 0 :(得分:4)

可以使用自定义ConfigurationProperties

来实现
@ConfigurationProperties("application")
public class ApplicationClients {

    private final List<ApplicationClient> clients = new ArrayList<>();

    public List<ApplicationClient> getClients() {
        return this.clients;
    }

}

@Getter
@Setter
public class ApplicationClient {
    private String username;
    private String password;
    private String[] roles;
}

@Configuration
@EnableConfigurationProperties(ApplicationClients.class)
public class AuthenticationManagerConfig extends
        GlobalAuthenticationConfigurerAdapter {

    @Autowired
    ApplicationClients application;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        for (ApplicationClient client : application.getClients()) {
            auth.inMemoryAuthentication()
                    .withUser(client.getUsername()).password(client.getPassword()).roles(client.getRoles());
        }
    }

}

然后您可以在application.yml中指定用户:

application:
  clients:
    - username: rw
      password: rw
      roles: READ,WRITE
    - username: r
      password: r
      roles: READ
    - username: w
      password: w
      roles: WRITE

不要忘记将spring-boot-configuration-processor添加到您的build.gradle

compile 'org.springframework.boot:spring-boot-configuration-processor'

2018年4月更新

对于 Spring Boot 2.0 ,我使用以下类:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableWebSecurity
@ConditionalOnWebApplication
@EnableConfigurationProperties(ApplicationClients.class)
@RequiredArgsConstructor
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final ApplicationClients application;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .requestMatchers(EndpointRequest.to("health")).permitAll()
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ACTUATOR")
            .antMatchers("/rest/**").authenticated()
            .antMatchers("/soap/**").authenticated()
            .and()
            .cors()
            .and()
            .httpBasic();
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        final InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        log.info("Importing {} clients:", application.getClients().size());

        application.getClients().forEach(client -> {
            manager.createUser(User.withDefaultPasswordEncoder()
                .username(client.getUsername())
                .password(client.getPassword())
                .roles(client.getRoles())
                .build());
            log.info("Imported client {}", client.toString());
        });

        return manager;
    }
}

请注意,由于安全问题,User.withDefaultPasswordEncoder()已被标记为已弃用。