注解使用
Spring Security默认是禁用注解的,要想开启注解,需要加上@EnableMethodSecurity注解
- 使用@Secured需要在配置类中添加注解***@EnableGlobalMethodSecurity(securedEnabled=true)***才能生效
- 使用@PreAuthorize和@PostAuthorize需要在配置类中配置注解***@EnableGlobalMethodSecurity(prePostEnable=true)***才能生效
注解方法
- hasAuthority(String):判断角色是否具有特定权限
http.authorizeRequests().antMatchers(“/main1.html”).hasAuthority(“admin”)
- hasAnyAuthority(String …):如果用户具备给定权限中某一个,就允许访问
http.authorizeRequests().antMatchers(“/admin/read”).hasAnyAuthority(“xxx”,“xxx”)
- hasRole(String):如果用户具备给定角色就允许访问,否则出现403
http.authorizeRequests().antMatchers(“/admin/read”).hasRole(“ROLE_管理员”)
- hasAnyRole(String …):如果用户具备给定角色的任意一个,就允许被访问
http.authorizeRequests().antMatchers(“/guest/read”).hasAnyRole(“ROLE_管理员”, “ROLE_访客”)
- hasIpAddress(String):请求是指定的IP就允许访问
http.authorizeRequests().antMatchers(“/ip”).hasIpAddress(“127.0.0.1”)
- permitAll():允许所有人(可无任何权限)访问
- denyAll():不允许任何(即使有最大权限)访问。
- isAnonymous():为可匿名(不登录)访问。
- isAuthenticated():为身份证认证后访问。
- isRememberMe():为记住我用户操作访问。
- isFullyAuthenticated():为非匿名且非记住我用户允许访问
@Secured
角色校验,请求到来访问控制单元方法时必须包含XX角色才能访问
注意:
- 角色必须添加ROLE_前缀
- 如果要求只有同时拥有admin和user的用户才能访问某个方法时,@Secured就无能为力了
@Component
public class UserDetailServiceImpl implements UserDetailsService {
@Resource
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username.equals("root")) {
return new User(username, passwordEncoder.encode("123"), AuthorityUtils.createAuthorityList("ROLE_read"));
} else if (username.equals("user")) {
return new User(username, passwordEncoder.encode("123"), AuthorityUtils.createAuthorityList("ROLE_write"));
}
return new User(username, passwordEncoder.encode("123"), AuthorityUtils.createAuthorityList("read"));
}
}
@RestController
public class HelloController {
@RequestMapping("/read")
@Secured(value = {
"ROLE_read"})
public String read() {
return "read";
}
@RequestMapping("/write")
@Secured(value = {
"ROLE_write"})
public String write() {
return "write";
}
// 错误实例
@RequestMapping("/read2")
@Secured(value = {
"read"})