一、权限管理
1 什么是权限管理?
权限管理实现对用户访问系统的控制,按照安全规则或者某种安全策略控制用户可以访问而且只能自己访问的授权资源。
权限管理包括身份认证和授权,简称认证授权,对于需要访问控制的资源用户需要先通过身份认证,认证通过后,用户具有该资源的访问权限才能访问。
2 什么是身份认证?
身份认证就是判断一个用户是否为合法用户的过程,最常用最简单的认证就是输入账号和密码,看账号是否存在于数据库中,密码时候和数据库中的密码相同,来判断用户身份是否正确。对于采用指纹等系统,则出示指纹;对于硬件Key等刷卡系统,则需要刷卡。
3 什么是授权?
授权就是访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的
二、shiro框架
1.Subject
主体,可以看到主体可以是任何可以与应用交互的 “用户”
2.SecurityManager
相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理
3.Authenticator
认证器,负责主体认证的,这是一个扩展点,如果用户觉得 Shiro 默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了
4.Authorizer
授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;
5.Realm
可以有 1 个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是 JDBC 实现,也可以是 LDAP 实现,或者内存实现等等;由用户提供;注意:Shiro 不知道你的用户 / 权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的 Realm;
6.SessionManager
如果写过 Servlet 就应该知道 Session 的概念,Session 呢需要有人去管理它的生命周期,这个组件就是 SessionManager;而 Shiro 并不仅仅可以用在 Web 环境,也可以用在如普通的 JavaSE 环境、EJB 等环境;所以呢,Shiro 就抽象了一个自己的 Session 来管理主体与应用之间交互的数据;这样的话,比如我们在 Web 环境用,刚开始是一台 Web 服务器;接着又上了台 EJB 服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到 Memcached 服务器);
7.SessionDAO
DAO 大家都用过,数据访问对象,用于会话的 CRUD,比如我们想把 Session 保存到数据库,那么可以实现自己的 SessionDAO,通过如 JDBC 写到数据库;比如想把 Session 放到 Memcached 中,可以实现自己的 Memcached SessionDAO;另外 SessionDAO 中可以使用 Cache 进行缓存,以提高性能
8.CacheManager
缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
9.Cryptography
密码模块,Shiro 提供了一些常见的加密组件用于如密码加密 / 解密的
三、简单认证授权Demo
1. 引入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.3</version>
</dependency>
2. 引入shiro配置文件
配置文件:名称随意,以 .ini 结尾,放在 resources 目录下
[users]
zhang=123
wang=123
4. 开发代码
package com.shiro.shirodemo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
public class test01 {
public static void main(String[] args) {
//1.创建安全管理器对象
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//2.给安全管理器设置realm
securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
//3.SecurityUtils给全局安全工具类设置安全管理器
SecurityUtils.setSecurityManager(securityManager);
//4.关键对象subject主体
Subject subject = SecurityUtils.getSubject();
//5.创建令牌
UsernamePasswordToken token = new UsernamePasswordToken("wang","123");
try {
System.out.println("认证状态"+subject.isAuthenticated());//fasle
//用户认证
subject.login(token);
System.out.println("认证状态"+subject.isAuthenticated());
}catch (UnknownAccountException e){
e.printStackTrace();
System.out.println("认证失败,用户名不存在");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("认证失败,密码错误");
}
}
}
5. 常见异常类型
- DisabledAccountException(帐号被禁用)
- LockedAccountException(帐号被锁定)
- ExcessiveAttemptsException(登录失败次数过多)
- ExpiredCredentialsException(凭证过期)等
四、自定义Realm
1. Realm类结构图
2. 认证源码
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info = getCachedAuthenticationInfo(token);
if (info == null) {
//otherwise not cached, perform the lookup:
info = doGetAuthenticationInfo(token);
log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
if (token != null && info != null) {
cacheAuthenticationInfoIfPossible(token, info);
}
} else {
log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
}
if (info != null) {
assertCredentialsMatch(token, info);
} else {
log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
}
return info;
}
doGetAuthenticationInfo 验证账号是否存在入口
assertCredentialsMatch 验证密码是否正确入口
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
SimpleAccount account = getUser(upToken.getUsername());
if (account != null) {
if (account.isLocked()) {
throw new LockedAccountException("Account [" + account + "] is locked.");
}
if (account.isCredentialsExpired()) {
String msg = "The credentials for account [" + account + "] are expired";
throw new ExpiredCredentialsException(msg);
}
}
return account;
}
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
CredentialsMatcher cm = getCredentialsMatcher();
if (cm != null) {
if (!cm.doCredentialsMatch(token, info)) {
//not successful - throw an exception to indicate this:
String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
} else {
throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
"credentials during authentication. If you do not wish for credentials to be examined, you " +
"can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
}
}
3. 解析源码
在整个Realm结构图中,shiro框架使用认证的方法是重写AuthenticatingRealm中的抽象方法doGetAuthenticationInfo,授权是重写了AuthorizingRealm中的抽象方法doGetAuthorizationInfo,而AuthorizingRealm是继承了AuthenticatingRealm,所以默认实现是SimpleAccountRealm继承了AuthorizingRealm,并且重写了doGetAuthenticationInfo和doGetAuthorizationInfo这两个方法,类继承关系请看上面的接口图,所以要自定义Realm需要继承AuthorizingRealm抽象类并且重写认证和授权的两个方法。
4. 代码实现
package com.shiro.shirodemo.config;
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;
import org.apache.shiro.util.ByteSource;
public class MyRealm1 extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String primaryPrincipal = (String)principals.getPrimaryPrincipal();
//用户名
System.out.println("身份信息: "+primaryPrincipal);
//根据身份信息 用户名 获取当前用户的角色信息,以及权限信息
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//假设 admin,user 是从数据库查到的 角色信息
simpleAuthorizationInfo.addRole("admin");
simpleAuthorizationInfo.addRole("user");
//假设 ... 是从数据库查到的 权限信息赋值给权限对象
simpleAuthorizationInfo.addStringPermission("user:*:01");
//第三个参数为*省略
simpleAuthorizationInfo.addStringPermission("prodect:*");
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String) token.getPrincipal();
String username = "zhangsan";
//模仿md5加密后的密码
String password = "9c3b5c0672cd599ccf1019bddaa8089b";
if (username.equals(principal)) {
return new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes("123"), this.getName());
}
return null;
}
}
package com.shiro.shirodemo.test;
import com.shiro.shirodemo.config.MyRealm1;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import java.util.Arrays;
public class TestAuthenticatorCustomerRealm {
public static void main(String[] args) {
//1.创建安全管理对象 securityManager
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
//2.给安全管理器设置realm(设置为自定义realm获取认证数据)
MyRealm1 myRealm1 = new MyRealm1();
//自定义密码认证器
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//加密方式为md5
hashedCredentialsMatcher.setHashAlgorithmName("md5");
//三列函数设置为1024
hashedCredentialsMatcher.setHashIterations(1024);
myRealm1.setCredentialsMatcher(hashedCredentialsMatcher);
defaultSecurityManager.setRealm(myRealm1);
//3.给安装工具类中设置默认安全管理器
SecurityUtils.setSecurityManager(defaultSecurityManager);
//4.获取主体对象subject
Subject subject = SecurityUtils.getSubject();
//5.创建token令牌
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
try {
subject.login(token);
System.out.println("登录成功~~");
} catch (UnknownAccountException e) {
e.printStackTrace();
System.out.println("用户名错误!!");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("密码错误!!!");
}
//授权
if (subject.isAuthenticated()){
//基于角色权限控制
System.out.println(subject.hasRole("admin"));
//基于多角色的权限控制
System.out.println(subject.hasAllRoles(Arrays.asList("admin", "user")));//true
System.out.println(subject.hasAllRoles(Arrays.asList("admin", "manager")));//false
//是否具有其中一个角色
boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "user", "manager"));
for (boolean aBoolean : booleans) {
System.out.println(aBoolean);
}
//基于权限字符串的访问控制 资源标识符:操作:资源类型
//用户具有的权限 user:*:01 prodect:*
System.out.println("权限:"+subject.isPermitted("user:update:01"));
System.out.println("权限:"+subject.isPermitted("prodect:update:02"));
//分别具有哪些权限
boolean[] permitted = subject.isPermitted("user:*:01", "user:update:02");
for (boolean b : permitted) {
System.out.println(b);
}
//同时具有哪些权限
boolean permittedAll = subject.isPermittedAll("prodect:*:01", "prodect:update:03");
System.out.println(permittedAll);
}
}
}
package com.shiro.shirodemo.test;
import org.apache.shiro.crypto.hash.Md5Hash;
public class Md5Test {
public static void main(String[] args) {
Md5Hash hash1 = new Md5Hash("123");
System.out.println(hash1.toHex());
Md5Hash hash2 = new Md5Hash("123","123");
System.out.println(hash2.toHex());
Md5Hash hash3 = new Md5Hash("123","123",1024);
System.out.println(hash3.toHex());
}
}