配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//your web request security config
http
.authorizeRequests()
.antMatchers("/")
.permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
;
//h2 console security config
http
.authorizeRequests()
.antMatchers("/h2-console/**")
.hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.csrf().ignoringAntMatchers("/h2-console/**")
.and()
.headers().frameOptions().sameOrigin()
;
}
@Bean
@Override
public UserDetailsService userDetailsService() {
//添加两个默认用户到内存
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
UserDetails admin = User
.withUsername("admin")
.password("admin")
.passwordEncoder(encoder::encode)
.roles("ADMIN")
.build();
UserDetails user = User
.withUsername("user")
.password("user")
.passwordEncoder(encoder::encode)
.roles("USER")
.build();
return new InMemoryUserDetailsManager(admin, user);
}
}
#spring.datasource
spring.datasource.jdbc-url=jdbc:h2:file:~/.h2/dev
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
#spring.h2
spring.h2.console.settings.web-allow-others=true
spring.h2.console.path=/h2-console
spring.h2.console.enabled=true