基于角色或权限进行访问控制
hasAuthority 方法
如果当前的主体具有指定的权限,则返回 true,否则返回 false
在配置类设置当前访问地址有哪些
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写的登陆页面
.loginPage("/login.html") //登陆页面设置
.loginProcessingUrl("/user/login") //登陆访问路径
.defaultSuccessUrl("/test/index").permitAll() //登陆成功之后,跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问,不需要认证
//当前登陆用户,只有具有admin权限才可以访问这个路径
.antMatchers("/test/index").hasAuthority("admins")
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf防护
}
在UserDetailsService,把返回User对象设置权限
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用userMapper方法,根据用户名查询数据库
QueryWrapper<Users> wrapper = new QueryWrapper<>();
//where username = ?
wrapper.eq("username",username);
Users users = usersMapper.selectOne(wrapper);
//判断
if (users==null)//数据库没有用户名,认证失败
{
throw new UsernameNotFoundException("用户名不存在!");
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
}
测试
没有访问权限 403
hasAnyAuthority 方法
如果当前的主体有任何提供的“角色”的话,返回true.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写的登陆页面
.loginPage("/login.html") //登陆页面设置
.loginProcessingUrl("/user/login") //登陆访问路径
.defaultSuccessUrl("/test/index").permitAll() //登陆成功之后,跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问,不需要认证
// //当前登陆用户,只有具有admin权限才可以访问这个路径
// .antMatchers("/test/index").hasAuthority("admins")
.antMatchers("/test/index").hasAnyAuthority("admins”,“manager")
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf防护
}
hasRole 方法
如果用户具备给定角色就允许访问,否则出现 403。
如果当前主体具有指定的角色,则返回 true。
从源码中我们可以看出,前面会自动加个ROLE_
hasAnyRole
表示用户具备任何一个条件都可以访问。
版权声明:本文为m0_51955470原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。