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

use*_*453 3 spring spring-security spring-boot spring-boot-actuator

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

security:
  basic:
    enabled: true
  user:
    name: admin
    password: admin
    role: EXAMPLE
Run Code Online (Sandbox Code Playgroud)

但是,@RolesAllowed("READ")即使我假设用户admin不应该访问该方法,我仍然能够访问带有注释的 方法。我的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();

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

use*_*453 6

可以通过custom实现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());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

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

application:
  clients:
    - username: rw
      password: rw
      roles: READ,WRITE
    - username: r
      password: r
      roles: READ
    - username: w
      password: w
      roles: WRITE
Run Code Online (Sandbox Code Playgroud)

别忘了添加spring-boot-configuration-processor到您的build.gradle

compile 'org.springframework.boot:spring-boot-configuration-processor'
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住,User.withDefaultPasswordEncoder()出于安全考虑,该标记已弃用。