在 application.yml 中定义基本安全用户、密码和角色
Define basic-security users, passwords and roles in application.yml
我正在寻找一种使用 Spring Boot 的 @Secured
注释来保护方法的方法。对于大约 10-15 个用户,我不想连接到数据库并从那里获取用户及其 authorities/roles,而是将它们存储在本地特定于配置文件的 application.yml
文件中。 Spring Boot 中有支持这个想法的概念吗?到目前为止,我能找到的所有内容都适用于基本安全执行器 ('org.springframework.boot:spring-boot-starter-security'
),看起来像这样:
security:
basic:
enabled: true
user:
name: admin
password: admin
role: EXAMPLE
但是,我仍然能够访问用 @RolesAllowed("READ")
注释的方法,即使我假设用户 admin 不应该访问所述方法。我的安全配置如下所示:
@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
别忘了将 spring-boot-configuration-processor
添加到您的 build.gradle
:
compile 'org.springframework.boot:spring-boot-configuration-processor'
2018 年 4 月更新
对于Spring Boot 2.0,我使用以下class:
@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 的 @Secured
注释来保护方法的方法。对于大约 10-15 个用户,我不想连接到数据库并从那里获取用户及其 authorities/roles,而是将它们存储在本地特定于配置文件的 application.yml
文件中。 Spring Boot 中有支持这个想法的概念吗?到目前为止,我能找到的所有内容都适用于基本安全执行器 ('org.springframework.boot:spring-boot-starter-security'
),看起来像这样:
security:
basic:
enabled: true
user:
name: admin
password: admin
role: EXAMPLE
但是,我仍然能够访问用 @RolesAllowed("READ")
注释的方法,即使我假设用户 admin 不应该访问所述方法。我的安全配置如下所示:
@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
别忘了将 spring-boot-configuration-processor
添加到您的 build.gradle
:
compile 'org.springframework.boot:spring-boot-configuration-processor'
2018 年 4 月更新
对于Spring Boot 2.0,我使用以下class:
@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()
已被标记为已弃用。