yml配置
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId> spring- boot- starter- security</artifactId>
</dependency>
新建一个SecurityConfig配置类
import org. springframework. security. config. annotation. authentication. builders. AuthenticationManagerBuilder ;
import org. springframework. security. config. annotation. web. builders. HttpSecurity ;
import org. springframework. security. config. annotation. web. configuration. WebSecurityConfigurerAdapter ;
import org. springframework. security. crypto. bcrypt. BCryptPasswordEncoder ;
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure ( HttpSecurity http) throws Exception {
http. authorizeRequests ( )
. antMatchers ( "/" ) . permitAll ( )
. antMatchers ( "/level1/**" ) . hasRole ( "vip1" )
. antMatchers ( "/level2/**" ) . hasRole ( "vip2" )
. antMatchers ( "/level3/**" ) . hasRole ( "vip3" ) ;
http. formLogin ( ) ;
}
@Override
protected void configure ( AuthenticationManagerBuilder auth) throws Exception {
auth. inMemoryAuthentication ( ) . passwordEncoder ( new BCryptPasswordEncoder ( ) )
. withUser ( "username" ) . password ( new BCryptPasswordEncoder ( ) . encode ( "123456" ) ) . roles ( "vip1" , "vip2" )
. and ( )
. withUser ( "root" ) . password ( new BCryptPasswordEncoder ( ) . encode ( "123456" ) ) . roles ( "vip1" , "vip2" , "vip3" )
. and ( )
. withUser ( "test" ) . password ( new BCryptPasswordEncoder ( ) . encode ( "123456" ) ) . roles ( "vip1" ) ;
}
}
import javax. sql. DataSource ;
@Autowired
private DataSource dataSource;
@Override
protected void configure ( AuthenticationManagerBuilder auth) throws Exception {
auth. jdbcAuthentication ( )
. dataSource ( dataSource)
. usersByUsernameQuery ( "select username,password,enabled from users WHERE username=?" )
. authoritiesByUsernameQuery ( "select username,authority from authorities where username=?" )
. passwordEncoder ( new BCryptPasswordEncoder ( ) ) ;
}