其他分享
首页 > 其他分享> > 春季-在application.yml中定义基本安全性用户,密码和角色

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

作者:互联网

我正在寻找一种使用Spring Boot的@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

但是,即使我假设用户管理员不应该访问该方法,我仍然能够访问带有@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中指定多个具有不同密码和不同角色的用户,并注释方法以确保只有授权用户才能访问这些方法.

解决方法:

可以使用自定义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

不要忘记在您的build.gradle中添加spring-boot-configuration-processor:

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()已被标记为已弃用.

标签:spring-boot-actuator,spring-boot,spring-security,spring
来源: https://codeday.me/bug/20191026/1937969.html