springboot整合springsecurity

案例

本案例以springboot整合springsecurity和thymeleaf俩进行实现
1、引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

2、配置自定义Security管理类,继承WebSecurityConfigurerAdapter类,添加注解@EnableWebSecurity交给springboot管理

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/first/*").hasAnyRole("vip1")
                .antMatchers("/second/*").hasAnyRole("vip2")
                .antMatchers("/third/*").hasAnyRole("vip3");
        http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
        http.rememberMe().rememberMeParameter("rememberMe");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhang1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("zhang2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
                .and()
                .withUser("zhang3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}


版权声明:本文为qq_43803695原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。