SpringSecurity(06)——权限注解

注解使用

Spring Security默认是禁用注解的,要想开启注解,需要加上@EnableMethodSecurity注解

  1. 使用@Secured需要在配置类中添加注解***@EnableGlobalMethodSecurity(securedEnabled=true)***才能生效
  2. 使用@PreAuthorize和@PostAuthorize需要在配置类中配置注解***@EnableGlobalMethodSecurity(prePostEnable=true)***才能生效

注解方法

  1. hasAuthority(String):判断角色是否具有特定权限

http.authorizeRequests().antMatchers(“/main1.html”).hasAuthority(“admin”)

  1. hasAnyAuthority(String …):如果用户具备给定权限中某一个,就允许访问

http.authorizeRequests().antMatchers(“/admin/read”).hasAnyAuthority(“xxx”,“xxx”)

  1. hasRole(String):如果用户具备给定角色就允许访问,否则出现403

http.authorizeRequests().antMatchers(“/admin/read”).hasRole(“ROLE_管理员”)

  1. hasAnyRole(String …):如果用户具备给定角色的任意一个,就允许被访问

http.authorizeRequests().antMatchers(“/guest/read”).hasAnyRole(“ROLE_管理员”, “ROLE_访客”)

  1. hasIpAddress(String):请求是指定的IP就允许访问

http.authorizeRequests().antMatchers(“/ip”).hasIpAddress(“127.0.0.1”)

  1. permitAll():允许所有人(可无任何权限)访问
  2. denyAll():不允许任何(即使有最大权限)访问。
  3. isAnonymous():为可匿名(不登录)访问。
  4. isAuthenticated():为身份证认证后访问。
  5. isRememberMe():为记住我用户操作访问。
  6. isFullyAuthenticated():为非匿名且非记住我用户允许访问

@Secured

角色校验,请求到来访问控制单元方法时必须包含XX角色才能访问

注意:

  1. 角色必须添加ROLE_前缀
  2. 如果要求只有同时拥有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"})
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值