我們來看下項目結構
配置類分兩個包prod 、test
WebSecurityProdConfig.java
/**
* @desc 生產配置類
* @Auth 姚仲傑
* @Date 2019/8/15 9:54
**/
@Configuration
@EnableWebSecurity
@Profile(value = {"prod"})
public class WebSecurityProdConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated();
http.formLogin().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin"))
.roles("admin");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
WebSecurityDevConfig.java
/**
* @desc 安全配置類
* @Auth 姚仲傑
* @Date 2019/8/15 9:27
**/
@Configuration
@EnableWebSecurity
@Profile(value = {"dev","test"})
public class WebSecurityDevConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated();
http.formLogin().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/user/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin"))
.roles("admin");
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
以上兩個類除了 類頭註解不一樣 還有 下面這個地方不一樣
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/user/**");
}
現在來寫個controller,簡單點返回個id 就看下 能不能調用
/**
* @desc controller
* @Auth 姚仲傑
* @Date 2019/8/15 9:37
**/
@RestController
public class UserController {
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") String id){
return id;
}
}
現在配置 application.properties
server.port=8080
spring.profiles.active=dev
#當這個爲dev的時候就不會攔截 /user/1
#當這個爲prod的時候就訪問 /user/1 就會被跳轉到登入頁面
#不信?你試試