shiro

tech2026-10-08  4

shiro简介

pache Shiro是Java的一个安全框架。功能强大,使用简单的Java安全框架,它为开发人员提供一个直观而全面的认证,授权,加密及会话管理的解决方案。

​ 实际上,Shiro的主要功能是管理应用程序中与安全相关的全部,同时尽可能支持多种实现方法。Shiro是建立在完善的接口驱动设计和面向对象原则之上的,支持各种自定义行为。Shiro提供的默认实现,使其能完成与其他安全框架同样的功能,这不也是我们一直努力想要得到的吗!

​ Apache Shiro相当简单,对比Spring Security,可能没有Spring Security做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的Shiro就足够了。对于它俩到底哪个好,这个不必纠结,能更简单的解决项目问题就好了。

​ Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。Shiro可以帮助我们完成:认证、授权、加密、会话管理、与Web集成、缓存等。这不就是我们想要的嘛,而且Shiro的API也是非常简单。

结构

1.外部结构

Shiro的对外API核心就是Subject;其每个API的含义:

Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者;

SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过SpringMVC,你可以把它看成DispatcherServlet前端控制器;

Realm:域,Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。

也就是说对于我们而言,最简单的一个Shiro应用:

1、应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager; 2、我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其 权限进行判断。

从以上也可以看出,Shiro不提供维护用户/权限,而是通过Realm让开发人员自己注入。

2.内部结构

Subject:主体,可以看到主体可以是任何可以与应用交互的“用户”;

SecurityManager:相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。

Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;

Authrizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;

Realm:可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;

SessionManager:如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器);

SessionDAO:DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能;

CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能

Cryptography:密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的。

shiro中的过滤器

shiro框架内置了10个过滤器,我们学习3个 anon authc perms

过滤器简称对应的java类anonorg.apache.shiro.web.filter.authc.AnonymousFilterauthcorg.apache.shiro.web.filter.authc.FormAuthenticationFilterauthcBasicorg.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilterpermsorg.apache.shiro.web.filter.authz.PermissionsAuthorizationFilterportorg.apache.shiro.web.filter.authz.PortFilterrestorg.apache.shiro.web.filter.authz.HttpMethodPermissionFilterrolesorg.apache.shiro.web.filter.authz.RolesAuthorizationFiltersslorg.apache.shiro.web.filter.authz.SslFilteruserorg.apache.shiro.web.filter.authc.UserFilterlogoutorg.apache.shiro.web.filter.authc.LogoutFilter

JSP中的Shiro标签

标签名称标签条件(均是显示标签内容)shiro:authenticated登录之后shiro:notAuthenticated不在登录状态时shiro:guest用户在没有RememberMe时shiro:user用户在RememberMe时<shiro:hasAnyRoles name=“abc,123” >在有abc或者123角色时<shiro:hasRole name=“abc”>拥有角色abc<shiro:lacksRole name=“abc”>没有角色abc<shiro:hasPermission name=“abc”>拥有权限资源abc<shiro:lacksPermission name=“abc”>没有abc权限资源shiro:principal默认显示用户名称

Shiro的用户认证(spring中)

1. 依赖

<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> <!--shiro核心包--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.3.2</version> </dependency>

2.web.xml配置

<!-- Shiro Security filter filter-name这个名字的值将来还会在spring中用到--> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

3.配置文件applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- filter-name这个名字的值来自于web.xml中filter的名字 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <!--登录页面 如果没有登录 访问项目的方法或页面 直接跳转到这个页面 --> <property name="loginUrl" value="/login.jsp"></property> <!--登录后 在访问没有经过授权的方法或页面时 直接跳转到这个页面 --> <property name="unauthorizedUrl" value="/unauthorized.jsp"></property> <property name="filterChainDefinitions"> <!-- /**代表下面的多级目录也过滤 过滤器链 --> <value> /login.jsp = anon /css/** = anon /img/** = anon /plugins/** = anon /make/** = anon /login.do = anon /** = authc </value> </property> </bean> <!-- 引用自定义的realm <bean id="saasRealm" class="cn.itcast.realm.SaasRealm"/> --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- <property name="realm" ref="saasRealm"/>--> </bean> <!-- 安全管理器 --> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 生成代理,通过代理进行控制 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true"/> </bean> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans>

4.认证方法

@RequestMapping("/login") public String login(String email, String password) { // 做非空判断 if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){ request.setAttribute("error","邮箱或密码不能为空"); return "forward:login.jsp"; } // 使用shiro的认证方式:1、创建令牌 2、获取主题 3、开始认证 password = new Md5Hash(password, email, 2).toString();//把页面上输入的明文的密码转成密文的 UsernamePasswordToken token = new UsernamePasswordToken(email,password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); } catch (AuthenticationException e) { // e.printStackTrace(); request.setAttribute("error","邮箱或者密码有误"); return "forward:login.jsp"; } User user = (User) subject.getPrincipal(); //从shiro中获取当前登录人 // 把当前登录人放入到session session.setAttribute("loginUser",user); List<Module> moduleList = moduleService.findModuleListByUser(user); session.setAttribute("modules",moduleList); return "home/main"; }

需要自定义realm认证

import cn.itcast.domain.system.Module; import cn.itcast.domain.system.User; import cn.itcast.service.system.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; 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.springframework.beans.factory.annotation.Autowired; import java.util.List; public class SaasRealm extends AuthorizingRealm { @Autowired private UserService userService; // 认证 ,在方法中完成email和password的校验 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("+++++进入了认证方法AuthenticationInfo"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String email = token.getUsername(); String password_page = new String(token.getPassword()); User user = userService.findByEmail(email); //从数据库中查询 if(user!=null){ // 匹配密码 String password_db = user.getPassword(); if(password_db.equals(password_page)){ return new SimpleAuthenticationInfo(user,password_db,getName()); //Object principal, Object credentials 密码, String realmName 当前realm的类名 } } return null; //没有用户 } // 授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } }

授权 --(不完整)

@Autowired private ModuleService moduleService; // 授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // 告诉shiro框架 当前登录人有哪些菜单权限 System.out.println("------进入了授权方法AuthorizationInfo"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); User user = (User) principalCollection.getPrimaryPrincipal(); // 根据用户查询所拥有的菜单权限 List<Module> moduleList = moduleService.findModuleListByUser(user); for (Module module : moduleList) { authorizationInfo.addStringPermission(module.getCpermission()); } return authorizationInfo; }
最新回复(0)