默认方法级权限控制是关闭的,要手动开启@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //默认方法级权限控制是关闭的,要手动开启
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login/page")
.loginProcessingUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/login/page").permitAll()
.anyRequest().authenticated()
;
http.csrf().disable();
}
}
给方法添加权限控制@PreAuthorize("hasAuthority('aa')") @PreAuthorize("hasRole('ADMIN')")
@RestController
public class HelloController {
@RequestMapping("hello")
public String hell() {
return "Hello World";
}
@PreAuthorize("hasAuthority('aa')")
@RequestMapping("say")
public String say() {
return "say...";
}
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping("run")
public String run() {
return "run...";
}
}
给用户权限和角色
@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {
@Autowired
public PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//模拟用户可以在数据库查询到
if ("devin".equals(username)) {
return new User("devin", passwordEncoder.encode("1234"),
//这个给的权限标识符为 aa, 角色为ROLE_ADMIN(这里要注意加上前缀ROLE_标识是角色)
AuthorityUtils.commaSeparatedStringToAuthorityList("aa, ROLE_ADMIN"));
}
throw new UsernameNotFoundException("用户名输入错误");
}
}
登录 devin/1234 因为有权限,所以都可以访问。