spring boot--在spring security下使用h2

配置

  • maven依赖
    <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>

  • 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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容