在Shiro中,需要从Realm(域)获取用来校验安全所需的数据,比如用户、角色、权限。

在执行的过程中,SecurityManager进行用户身份的验证,那么验证的数据从哪里获得呢?就是从Realm中获取。可以从Realm获取对用户进行认证的身份信息,对请求进行授权的角色、权限信息。

可以把Realm理解为DataSource,即安全数据源。

自定义Realm

自定义Realm通常继承AuthorizingRealm类,实现对应的方法即可。

public class PrincipalRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String name = "tom";
        String mobile = "156*********";
        String password = "123456";
        String salt = "abc";
        System.out.println("进行认证...");
        return new SimpleAuthenticationInfo(new Principal(name, mobile),
                password, ByteSource.Util.bytes(salt), getName());
    }
}

然后在构造SecurityManager环境时,将初始化的Realm添加即可。

// 1.构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(principalRealm);

多个Realm

上面的示例展示添加一个Realm,其实SecurityManager支持添加多个Realm的,只不过不再是使用setRealm方法,而替换为setRealms方法。

对应方法源码如下:

public void setRealms(Collection<Realm> realms) {
    if (realms == null) {
        throw new IllegalArgumentException("Realms collection argument cannot be null.");
    }
    if (realms.isEmpty()) {
        throw new IllegalArgumentException("Realms collection argument cannot be empty.");
    }
    this.realms = realms;
    afterRealmsSet();
}

可以看出,setRealms方法接收的是一个结合,但这个集合需要有序,SecurityManager会按照realms指定的顺序进行身份认证。

PrincipalRealm principalRealm = new PrincipalRealm();

// 1.构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
// 设置单个Realm
defaultSecurityManager.setRealm(principalRealm);

// 设置多个Realm
Set<Realm> realms = new LinkedHashSet<>();
realms.add(principalRealm);
defaultSecurityManager.setRealms(realms);

小结

以上便是Realm的功能,自定义示例,以及多个Realm的使用实例。



Shiro之Realm,自定义Realm和多个Realm插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.choupangxia.com/2021/01/29/shiro-realm/