前言

  这篇是很久之前学习Spring Security整理的博客,发现浏览量都1000多了,一个赞都没有,那说明写得确实不怎么样,哈哈。应该很多初学者对这个接口存在疑问,特别是如果学习这个框架之前还了解过Shiro,可能会因为这两个框架角色、权限的表示方式,产生困惑。现在重新整理一下。

GrantedAuthority接口

我们知道UserDeitails接口里面有一个getAuthorities()方法。这个方法将返回此用户的所拥有的权限。这个集合将用于用户的访问控制,也就是Authorization。

所谓权限,就是一个字符串。一般不会重复。

所谓权限检查,就是查看用户权限列表中是否含有匹配的字符串。

package org.springframework.security.core;

import java.io.Serializable;

public interface GrantedAuthority extends Serializable {
    String getAuthority();
}

"角色"如何表示?与Shiro有何不同?

在Security中,角色和权限共用GrantedAuthority接口,唯一的不同角色就是多了个前缀"ROLE_",而且它没有Shiro的那种从属关系,即一个角色包含哪些权限等等。在Security看来角色和权限时一样的,它认证的时候,把所有权限(角色、权限)都取出来,而不是分开验证。

所以,在Security提供的UserDetailsService默认实现JdbcDaoImpl中,角色和权限都存储在auhtorities表中。而不是像Shiro那样,角色有个roles表,权限有个permissions表。以及相关的管理表等等。

GrantedAuthority接口的默认实现SimpleGrantedAuthority

package org.springframework.security.core.authority;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

public final class SimpleGrantedAuthority implements GrantedAuthority {
    private static final long serialVersionUID = 500L;
    private final String role;

    public SimpleGrantedAuthority(String role) {
        Assert.hasText(role, "A granted authority textual representation is required");
        this.role = role;
    }

    public String getAuthority() {
        return this.role;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else {
            return obj instanceof SimpleGrantedAuthority ? this.role.equals(((SimpleGrantedAuthority)obj).role) : false;
        }
    }

    public int hashCode() {
        return this.role.hashCode();
    }

    public String toString() {
        return this.role;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-02-11
  • 2021-12-18
  • 2021-06-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
猜你喜欢
  • 2021-04-21
  • 2021-08-05
  • 2021-10-22
  • 2022-01-30
  • 2022-12-23
相关资源
相似解决方案