美文网首页权限安全
[java][shrio]:概念+spring集成

[java][shrio]:概念+spring集成

作者: 阿不不不不 | 来源:发表于2018-11-19 17:39 被阅读28次

    核心概念

    Subject:主体,可以看到主体可以是任何可以与应用交互的“用户”;
    SecurityManager:相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。
    Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
    Authorizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;
    Realm:可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;
    SessionManager:如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;可以实现分布式的会话管理;
    SessionDAO:DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到redis中,可以实现自己的redis  SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能;
    CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
    Cryptography:密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的。
    

    spring集成

    1、导入相关依赖
    <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.1.3</version>
            </dependency>
            <dependency>
                <groupId>commons-collections</groupId>
                <artifactId>commons-collections</artifactId>
                <version>3.2.1</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>1.2.2</version>
            </dependency>
            <dependency>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache-core</artifactId>
                <version>2.6.8</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-ehcache</artifactId>
                <version>1.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-quartz</artifactId>
                <version>1.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.2.2</version>
            </dependency>
    
    2.在web.xml配置ShiroFilter
    <!-- shiro过虑器,DelegatingFilterProx会从spring容器中找shiroFilter 必须放到web.xml前面-->
        <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.添加Shiro配置文件
    3.1自定义Realm
    <bean id="userRealm" class="com._520it.wms.realm.UserRealm"></bean>
    
    public class UserRealm extends AuthorizingRealm {
        @Override
        public String getName() {
            return "UserRealm";
        }
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            String principal = (String) token.getPrincipal();
            if(!"admin".equals(principal)){
                return null;
            }
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(),getName());
            return authenticationInfo;
        }
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            Employee currentUser = (Employee) principals.getPrimaryPrincipal();
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            List<String> roles = new ArrayList<String>();
            roles.addAll(Arrays.asList("HR MGR","ORDER MGR"));
            authorizationInfo.addRoles(roles);
            List<String> perms = new ArrayList<String>();
            perms.addAll(Arrays.asList("employee:view","employee:delete"));
            authorizationInfo.addStringPermissions(perms);
            return authorizationInfo;
        }
    }
    
    3.2安全管理器SecurityManager
    <!-- 配置安全管理器SecurityManager -->
    在applicationContext-shrio.xml中添加如下配置:
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"/>
    </bean>
    
    3.3Shiro的Web过滤器
    注意:名字必须要和web.xml中配置的名字一致
    在applicationContext-shrio.xml中添加如下配置:
    <!-- 定义ShiroFilter -->
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager"/>
            <property name="loginUrl" value="/login.action"/>
            <property name="successUrl" value="/main.action"/>
            <property name="unauthorizedUrl" value="/nopermission.jsp"/>
            <property name="filterChainDefinitions">
                <value>
                <!-- 静态资源不需要拦截-->
                    /js/**=anon
                    /images/**=anon
                    /style/**=anon
                    /logout.action=logout
                    /**=authc
                </value>
            </property>
        </bean>
    
    4.修改登录方法
        public String execute()throws Exception{
            HttpServletRequest req = ServletActionContext.getRequest();
            if(SecurityUtils.getSubject().isAuthenticated()){
                return "main";
            }
            String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
            //根据shiro返回的异常类路径判断,抛出指定异常信息
            if(exceptionClassName!=null){
                if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                    //最终会抛给异常处理器
                    super.addActionError("账号不存在");
                } else if (IncorrectCredentialsException.class.getName().equals(
                        exceptionClassName)) {
                    super.addActionError("用户名/密码错误");
                } else {
                    super.addActionError("其他异常信息");//最终在异常处理器生成未知错误
                }
            }
            return "login";
        }
    
    5.使用shiro注解授权
    在applicationContext-shrio.xml中添加如下配置:   
    <!-- 开启aop,对类代理 -->
        <aop:config proxy-target-class="true"></aop:config>
        <!-- 开启shiro注解支持 -->
        <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
            <property name="securityManager" ref="securityManager" />
        </bean>
    
    在需要控制的方法上贴上注解:@RequiresPermissions("employee:view")
    
    6.缓存管理
    7.会话管理
    <!--会话管理-->
    在applicationContext-shrio.xml中添加如下配置:
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
            <!-- session的失效时长,单位毫秒 -->
            <property name="globalSessionTimeout" value="60000"/>
            <!-- 删除失效的session -->
            <property name="deleteInvalidSessions" value="true"/>
    </bean>
    
    <!-- 配置安全管理器SecurityManager -->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="realm" ref="userRealm"/>
            <property name="cacheManager" ref="cacheManager"/>
            <property name="sessionManager" ref="sessionManager"/>
        </bean>
    
    8.添加凭证匹配器
    在applicationContext-shrio.xml中添加如下配置:
    <!--自定义realm-->
    <bean id="myRealm" class="com._520it.wms.realm.MyRealm">
       <property name="employeeService" ref="employeeService"/>
       <property name="roleService" ref="roleService"/>
       <property name="permissionService" ref="permissionService"/>
       <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>
    <!--添加凭证匹配器(为密码加盐操作)-->
     <bean id="credentialsMatcher"
            class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
            <property name="hashAlgorithmName" value="md5" />
            <property name="hashIterations" value="1" />
    </bean>
    
    9.通过数据库进行认证和授权

    常见注解

    @RequiresAuthentication
    验证用户是否登录,等同于方法subject.isAuthenticated() 结果为true时。
    
    @RequiresUser
    验证用户是否被记忆,user有两种含义:
    一种是成功登录的(subject.isAuthenticated() 结果为true);
    另外一种是被记忆的(subject.isRemembered()结果为true)。
    
    @RequiresGuest
    验证是否是一个guest的请求,与@RequiresUser完全相反。
     换言之,RequiresUser  == !RequiresGuest。
    此时subject.getPrincipal() 结果为null.
    
    @RequiresRoles
    例如:
    @RequiresRoles("aRoleName");
      void someMethod();
    如果subject中有aRoleName角色才可以访问方法someMethod。如果没有这个权限则会抛出异常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。
    
    @RequiresPermissions
    例如: 
    @RequiresPermissions({"file:read", "write:aFile.txt"} )
     void someMethod();
    要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。
    

    相关文章

      网友评论

        本文标题:[java][shrio]:概念+spring集成

        本文链接:https://www.haomeiwen.com/subject/fpegfqtx.html