目录结构
部分POM文件如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
security配置类,其中注意@EnableGlobalMethodSecurity(prePostEnabled = true)注解。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("user").roles("USER")
.and()
.withUser("admin").password("admin").roles("ADMIN")
.and()
.passwordEncoder(new MyPasswordEncoder())
;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
http
.authorizeRequests().antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
@Bean
@Override
protected UserDetailsService userDetailsService() {
return super.userDetailsService();
}
}
定义一个密码加密类:此处采用明文加密
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(rawPassword.toString());
}
}
controller如下:
@RestController
public class TestController {
@RequestMapping("/")
public String index(){
return "this is index page!";
}
@RequestMapping("/user")
@PreAuthorize("hasRole('USER')")
public String user(){
return "this is user page!";
}
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String admin(){
return "this is admin page!";
}
}
路径“/”所有用户都能访问,
/user路径只允许USER用户访问
/admin路径只允许ADMIN用户访问。
就这么多,包教不包会