部分引自 www.javaboy.org
在實(shí)際項(xiàng)目中肯定不能對(duì)所有接口都進(jìn)行攔截以舒,一般都有不同的訪問控制權(quán)限方案,在這種情況下需要配置不同的攔截規(guī)則擎颖,對(duì)不同的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中準(zhǔn)備接口
@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";
}
}
啟動(dòng)項(xiàng)目,然后使用不同用戶登錄測(cè)試訪問權(quán)限
loginProcessingUrl("/doLogin")意思是處理登錄的借口是 doLogin
搂捧,在這里并沒有什么實(shí)際意義驮俗,但是如果采取的是Postman做的,建議加一下
配置多個(gè)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) // 多個(gè)優(yōu)先級(jí)排序
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();
}
}
}
啟動(dòng)postman測(cè)試