SpringBoot整合Spring Security HttpSecurity的配置

部分引自 www.javaboy.org
在实际项目中肯定不能对所有接口都进行拦截,一般都有不同的访问控制权限方案,在这种情况下需要配置不同的拦截规则,对不同的url采取不同的策略,这就是HttpSecurity的作用

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("yzn").password("123").roles("admin")
                .and()
                .withUser("test").password("123").roles("user");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("admin","user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")
                .permitAll()
                .and()
                .csrf().disable();
    }
}

Controller中准备接口

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "hello user";
    }

}

启动项目,然后使用不同用户登录测试访问权限

loginProcessingUrl("/doLogin")意思是处理登录的借口是 doLogin,在这里并没有什么实际意义,但是如果采取的是Postman做的,建议加一下

配置多个HttpSecurity

@Configuration
public class MultiHttpSecurityConfig {
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("yzn").password("111").roles("admin")
                .and()
                .withUser("test").password("222").roles("user");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Configuration
    @Order(1) // 多个优先级排序
    public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasRole("admin");
        }
    }

    @Configuration
    public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginProcessingUrl("/doLogin")
                    .permitAll()
                    .and()
                    .csrf().disable();
        }
    }
}

启动postman测试

你可能感兴趣的:(SpringBoot整合Spring Security HttpSecurity的配置)