spring boot--在spring security下使用h2

配置

  • maven依赖
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.0.RELEASE
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-security
        
        
            com.h2database
            h2
            runtime
        
    

  • WebSecurityConfig
@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);
    }
}
  • application.properties
#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

你可能感兴趣的:(spring boot--在spring security下使用h2)