SpringSecurity设置角色和权限的注意点 - Go语言中文社区

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


概念

在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设计者的考虑,两种性质完成独立的东西,不存在任何关系,一个是用做角色控制,一个是操作权限的控制,二者也并不矛盾。

版权声明:本文来源博客园,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.cnblogs.com/lori/p/10396302.html
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-11-16 23:09:37
  • 阅读 ( 1005 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢