尚硅谷Security笔记
设置用户权限
有四种方法。
1.hasAuthority() 方法:只能给用户一个权限
@Override
public void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login.html") // 自定义 login 页面
.loginProcessingUrl("/user/login") // 登录的处理URL(controller)
.defaultSuccessUrl("/test/home").permitAll() // 登录成功后调转的页面
.and()
.authorizeRequests() // 需要设置权限的请求
.antMatchers("/", "/test/hello", "/user/login").permitAll() // 不需要过滤的资源
// 1. hasAuthority() 只能给用户一个权限
.antMatchers("/test/home").hasAuthority("admin")
.anyRequest().authenticated() // 任何请求都可以访问
.and()
.csrf().disable();
}
2.hasAnyAuthority() 方法:可以给多个权限
@Override
public void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/user/login")
.defaultSuccessUrl("/test/home").permitAll()
.and()
.authorizeRequests()
.antMatchers("/", "/test/hello", "/user/login").permitAll()
// 2. hasAnyAuthority() 可以给多个权限
.antMatchers("/test/home").hasAnyAuthority("admin,manager")
.anyRequest().authenticated()
.and()
.csrf().disable();
}
3.hasRole()方法:只能给一个权限。
而且底层方法中,会给权限名加上【ROLE_】前缀。
@Override
public void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/user/login")
.defaultSuccessUrl("/test/home").permitAll()
.and()
.authorizeRequests()
.antMatchers("/", "/test/hello", "/user/login").permitAll()
// 3. hasRole()
.antMatchers("/test/home").hasRole("sale")
.anyRequest().authenticated()
.and()
.csrf().disable();
}
注意 hasRole(“sale”) 的参数是sale,下面代码的参数则是 ROLE_sale 才能成功运行。
@Service("userDetailsService")
public class CustomerUserDetailService implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<Users> wrapper = new QueryWrapper<>();
// 根据用户名查询
wrapper.eq("username", username);
// selectOne 返回一条结果
Users user = usersMapper.selectOne(wrapper);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), auths);
}
}
注意上面倒数第二行代码 AuthorityUtils.commaSeparatedStringToAuthorityList(“admin,ROLE_sale”);
4.hasAnyRole()
还有一种方法是 hasAnyRole() 和 hasAnyAuthority() 差不多,不写了,用的时候百度。