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

 更新时间:2022年03月12日 15:07:50   作者:张占岭  
这篇文章主要介绍了使用SpringSecurity设置角色和权限的注意点,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringSecurity设置角色和权限

概念

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

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

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

Security角色和权限的概念

Security中一些可选的表达式

  • permitAll永远返回true
  • denyAll永远返回false
  • anonymous当前用户是anonymous时返回true
  • rememberMe当前用户是rememberMe用户时返回true
  • authenticated当前用户不是anonymous时返回true
  • fullAuthenticated当前用户既不是anonymous也不是rememberMe用户时返回true
  • hasRole(role)用户拥有指定的角色权限时返回true
  • hasAnyRole([role1,role2])用户拥有任意一个指定的角色权限时返回true
  • hasAuthority(authority)用户拥有指定的权限时返回true
  • hasAnyAuthority([authority1,authority2])用户拥有任意一个指定的权限时返回true
  • hasIpAddress('192.168.1.0')请求发送的Ip匹配时返回true

看到上述的表达式,应该能发现一些问题,在Security中,似乎并没有严格区分角色和权限,

如果没有角色和权限的区别,只需要hasRole()函数就够了, hasAuthority()是做什么用的?

答:区别就是,hasRole()的权限名称需要用 "ROLE_" 开头,而hasAuthority()不需要,而且,这就是全部的区别。

在通常的系统设计中,我们区分角色和权限,但是,判断 “用户是不是管理员”,和判断 “是否拥有管理员权限”,在代码逻辑上,其实是完全一致的,角色是一种权限的象征,可以看做是权限的一种。因此,不区分角色和权限,本身就是合理的做法。

如果撇开别的问题不谈,只考虑权限的问题,我们可以将角色视为权限的一种,但是,角色是用户的固有属性,在用户管理上还是非常有必要的,在Security4中,处理“角色”(如RoleVoter、hasRole表达式等)的代码总是会添加ROLE_前缀,它更加方便开发者从两个不同的维度去设计权限。

Spring Security3 到 Spring Security4 的迁移文档:

http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-jc.html#m3to4-role-prefixing

S.O. (Stack Overflow)网站对这个问题的描述:

https://stackoverflow.com/questions/19525380/difference-between-role-and-grantedauthority-in-spring-security

Think of a GrantedAuthority as being a "permission" or a "right". Those "permissions" are (normally) expressed as strings (with the getAuthority() method). Those strings let you identify the permissions and let your voters decide if they grant access to something.

You can grant different GrantedAuthoritys (permissions) to users by putting them into the security context. You normally do that by implementing your own UserDetailsService that returns a UserDetails implementation that returns the needed GrantedAuthorities.

Roles (as they are used in many examples) are just "permissions" with a naming convention that says that a role is a GrantedAuthority that starts with the prefix ROLE_. There's nothing more. A role is just a GrantedAuthority - a "permission" - a "right". You see a lot of places in spring security where the role with its ROLE_ prefix is handled specially as e.g. in the RoleVoter, where the ROLE_ prefix is used as a default. This allows you to provide the role names withtout the ROLE_ prefix. Prior to Spring security 4, this special handling of "roles" has not been followed very consistently and authorities and roles were often treated the same (as you e.g. can see in the implementation of the hasAuthority() method in SecurityExpressionRoot - which simply calls hasRole()). With Spring Security 4, the treatment of roles is more consistent and code that deals with "roles" (like the RoleVoter, the hasRole expression etc.) always adds the ROLE_ prefix for you. So hasAuthority('ROLE_ADMIN') means the the same as hasRole('ADMIN') because the ROLE_ prefix gets added automatically. See the spring security 3 to 4 migration guide for futher information.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 从java源码分析线程池(池化技术)的实现原理

    从java源码分析线程池(池化技术)的实现原理

    这篇文章主要介绍了从java源码分析线程池(池化技术)的实现原理,池化技术是一种编程技巧,当程序出现高并发时,能够明显的优化程序,降低系统频繁创建销毁连接等额外开销,下文更多的相关介绍需要的小伙伴可以参考一下
    2022-04-04
  • Java中forEach使用lambda表达式,数组和集合的区别说明

    Java中forEach使用lambda表达式,数组和集合的区别说明

    这篇文章主要介绍了Java中forEach使用lambda表达式,数组和集合的区别说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Eclipse+Java+Swing实现斗地主游戏(代码)

    Eclipse+Java+Swing实现斗地主游戏(代码)

    这篇文章主要介绍了Eclipse+Java+Swing实现斗地主游戏并附上详细的代码实现,正在学习的你可以当小练习练练,希望对你有所帮助
    2022-01-01
  • Spring Boot使用Servlet及Filter过程详解

    Spring Boot使用Servlet及Filter过程详解

    这篇文章主要介绍了Spring Boot使用Servlet及Filter过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • 基于JavaMail的Java实现复杂邮件发送功能

    基于JavaMail的Java实现复杂邮件发送功能

    这篇文章主要为大家详细介绍了基于JavaMail的Java实现复杂邮件发送功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-09-09
  • Mybatis-Plus注入SQL原理分析

    Mybatis-Plus注入SQL原理分析

    本文主要介绍了Mybatis-Plus注入SQL原理分析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • 浅谈解决Hibernate懒加载的4种方式

    浅谈解决Hibernate懒加载的4种方式

    这篇文章主要介绍了浅谈解决Hibernate懒加载的4种方式,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • SpringBoot项目创建使用+配置文件+日志文件详解

    SpringBoot项目创建使用+配置文件+日志文件详解

    Spring的出现是为了简化 Java 程序开发,而 SpringBoot 的出现是为了简化 Spring 程序开发,这篇文章主要介绍了SpringBoot项目创建使用+配置文件+日志文件,需要的朋友可以参考下
    2023-02-02
  • SPRING FRAMEWORK BEAN作用域和生命周期原理解析

    SPRING FRAMEWORK BEAN作用域和生命周期原理解析

    这篇文章主要介绍了SPRING FRAMEWORK BEAN作用域和生命周期原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • java中stringBuilder的用法详解

    java中stringBuilder的用法详解

    这篇文章主要介绍了java中stringBuilder的用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07

最新评论