完整代码:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页进入系统所有人可以访问,功能页只有对应有权限的人才能访问
//请求授权的规则~
//链式编程
//授权
/**
* HTTP请求处理
*/
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/vip").hasAnyRole("vip","svip","ssvip") //给角色授权
.antMatchers("/user/svip").hasAnyRole("svip","ssvip")
.antMatchers("/user/**").hasRole("ssvip")
.and()
.csrf().disable();
//没有权限默认到登录页面。需要开启登录页面
http.formLogin();
}
@Autowired
DataSource dataSource;
/**
* 授权验证服务
*/
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
//内存中
/*auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("simm").password("123").roles("USER").and()
.withUser("admin").password("admin").roles("USER","ADMIN");*/
/* auth
.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())//在此处应用自定义PasswordEncoder
.withUser("root")
.password(new BCryptPasswordEncoder().encode("root"))
.roles("ssvip")
.and()
.withUser("user")
.password(new BCryptPasswordEncoder().encode("user"))
.roles("vip");
*/
//默认
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select user_name,user_password, 'true' as enabled from users WHERE user_name=?") //认证
.authoritiesByUsernameQuery("select user_name,user_role from users where user_name=?") //授权
.passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public BCryptPasswordEncoder BCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
我先做了一次内存认证,没有问题,认证和权限都可以成功,这里的权限是优先级,ssvip>svip>vip
点击去就是相应的内容页,这样的,三个页面,body都是一句话:
希望大神求解
user_role的数据改一下,WebExpressionVoter.vote打断点就能看到了