一、简介
Shiro 提供了一些常见的Realm 实现如JdbcRealm,从数据库获取相关用户名、密码等信息作为认证、授权数据来源,但是非常的不方便,JdbcRealm 对数据表名、字段名都有硬性规定,非常不灵活。
二、配置INI 文件
[main]
#自定义Reaml 实现认证、授权
realm=com.vincent.UserRealm
#securityManager 对象是配置文件提供的SecurityManager 默认对象
securityManager.realm=$realm
三、自定义Realm
Reaml 接口实现类有很多,继承体系结构如下:
CachingRealm 实现缓存的支持
AuthenticationRealm 实现对认证支持
AuthorizingRealm 实现对认证、授权的支持。通常都继承该Realm 实现Realm 自定义。
新建UserRealm.java
package com.vincent;
import java.util.List;
import java.util.Arrays;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm{
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
if(((String)principals.getPrimaryPrincipal()).equalsIgnoreCase("vincent")) {
//创建授权对