当前位置: 移动技术网 > IT编程>开发语言>Java > SpringSecurity设置角色和权限的注意点

SpringSecurity设置角色和权限的注意点

2019年02月19日  | 移动技术网IT编程  | 我要评论

概念

在userdetailsservice的loaduserbyusername方法里去构建当前登陆的用户时,你可以选择两种授权方法,即角色授权和权限授权,对应使用的代码是hasrole和hasauthority,而这两种方式在设置时也有不同,下面介绍一下:

  1. 角色授权:授权代码需要加role_前缀,controller上使用时不要加前缀
  2. 权限授权:设置和使用时,名称保持一至即可

使用,mock代码

@component
public class myuserdetailservice implements userdetailsservice {
  @autowired
  private passwordencoder passwordencoder;

  @override
  public userdetails loaduserbyusername(string name) throws usernamenotfoundexception {
    user user = new user(name,
        passwordencoder.encode("123456"),
        authorityutils.commaseparatedstringtoauthoritylist("read,role_user"));//设置权限和角色
    // 1. commaseparatedstringtoauthoritylist放入角色时需要加前缀role_,而在controller使用时不需要加role_前缀
    // 2. 放入的是权限时,不能加role_前缀,hasauthority与放入的权限名称对应即可
    return user;
  }
}

上面使用了两种授权方法,大家可以参考。

在controller中为方法添加权限控制

 @getmapping("/write")
  @preauthorize("hasauthority('write')")
  public string getwrite() {
    return "have a write authority";
  }

  @getmapping("/read")
  @preauthorize("hasauthority('read')")
  public string readdate() {
    return "have a read authority";
  }

  @getmapping("/read-or-write")
  @preauthorize("hasanyauthority('read','write')")
  public string readwritedate() {
    return "have a read or write authority";
  }

  @getmapping("/admin-role")
  @preauthorize("hasrole('admin')")
  public string readadmin() {
    return "have a admin role";
  }

  @getmapping("/user-role")
  @preauthorize("hasrole('user')")
  public string readuser() {
    return "have a user role";
  }

网上很多关于hasrole和hasauthority的文章,很多都说二者没有区别,但大叔认识,这是spring设计者的考虑,两种性质完成独立的东西,不存在任何关系,一个是用做角色控制,一个是操作权限的控制,二者也并不矛盾。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网