Shiro使用及原理(二)
步骤:
- 编写shiro-permission-realm.ini配置文件如下:
[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#将凭证匹配设置到realm
myRealm=shiro.PermissionRealm
#散列次数
credentialsMatcher.hashIterations=64
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm
- 编写自定义realm,重写认证及授权方法
public class PermissionRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//传入参数,用户认证凭证信息(SimpleAuthenticationInfo:认证方法返回的封装的认证信息)
//拿到用户名信息
String username = (String) principalCollection.getPrimaryPrincipal();
//模拟查询数据库:用户角色,权限
ArrayList<String> rolesList = new ArrayList<>();
ArrayList<String> permissionsList = new ArrayList<>();
//假设有role1角色
rolesList.add("role1");
//假设有此权限
permissionsList.add("user:delete");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRoles(rolesList);
simpleAuthorizationInfo.addStringPermissions(permissionsList);
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//通过用户名查询数据库,进行认证
//在token中拿到用户名
String username = (String) authenticationToken.getPrincipal();
//通过用户名查询数据库
if (!"zhangsan".equals(username)) {
return null;
}
//假设查询数据库
String passsword = "664f16cf4ce56a454f348d3bfea194df";
//info对象表示realm登录比对信息
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, passsword, ByteSource.Util.bytes("123"),getName());
return info;
}
}
- 编写测试类,测试用户登录、验证角色以及权限信息
public class PermissionTest {
@Test
public void testPermission() {
//构建SecurityManager工程对象
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission-realm.ini");
//通过工厂对象创建出SecurityManager对象
SecurityManager securityManager = factory.getInstance();
//绑定securityManager到当前运行系统中,让系统随时使用
SecurityUtils.setSecurityManager(securityManager);
//创建当前登录的主体,拿到此时的主体
Subject subject = SecurityUtils.getSubject();
//绑定主体登录的身份/凭证
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
subject.login(token);
// System.out.println(subject.hasRole("role1"));
// System.out.println(subject.hasAllRoles(Arrays.asList("role1","role2")));
// System.out.println(Arrays.toString(subject.hasRoles(Arrays.asList("role1","role2"))));
//是否拥有某一个权限
System.out.println(subject.isPermitted("user:delete"));
System.out.println(subject.hasRole("role1"));
}
}
补充:
本文中使用的是MD5加密方式,事先对密码进行加密
public class PasswordMD5 {
public static void main(String[] args) {
//MD5加密
Md5Hash md5Hash = new Md5Hash("666", "123", 64);
System.out.println(md5Hash);
}
}
本文对shiro的认证授权做简单测试!!!!!