• Shiro


    公司项目需要重构,以前没玩过shiro,之前的1.0安全登录那块是用shiro做的,就上网查了下资料,结果师傅告诉我2.0不需要用,2.0用很多微服务,到时候搞集群,shiro是把session自己封装处理的,而我们微服务如果用还是用session处理会很麻烦,所以直接舍弃shiro,看了这么长时间自己做个总结,防止以后用再来找资料,吼吼

      Apache Shiro 是一个强大易用的Java安全框架,提供了认证,授权,加密和会话管理功能,可为任何应用提供安全保障-从命令应用,移动应用到大型网络及企业应用。

    说白了就是用户模块的应用,用户的权限啊,角色之类的

    下载链接:shiiro.apache.org

     Maven里pom的依赖配置,具体版本看自己需求:

    <!-- Spring 整合Shiro需要的依赖 -->  
    <dependency>  
        <groupId>org.apache.shiro</groupId>  
        <artifactId>shiro-core</artifactId>  
        <version>1.2.1</version>  
    </dependency>  
    <dependency>  
        <groupId>org.apache.shiro</groupId>  
        <artifactId>shiro-web</artifactId>  
        <version>1.2.1</version>  
    </dependency>  
    <dependency>  
        <groupId>org.apache.shiro</groupId>  
        <artifactId>shiro-ehcache</artifactId>  
        <version>1.2.1</version>  
    </dependency>  
    <dependency>  
        <groupId>org.apache.shiro</groupId>  
        <artifactId>shiro-spring</artifactId>  
        <version>1.2.1</version>  
    </dependency> 

    包搞定了现在开始写代码,Shiro最重要的就是他的自定义拦截器的AuthorizingRealm类,我们需要根据自己的需求继承这个类并重写他的两个方法,注意这两个方法很像,别写错了

    package com.luo.shiro.realm;
    
    import java.util.HashSet;
    import java.util.Set;
    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.authc.UsernamePasswordToken;
    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 com.luo.util.DecriptUtil;
    
    public class MyShiroRealm extends AuthorizingRealm {
    
        //这里因为没有调用后台,直接默认只有一个用户("admin","123456")
        private static final String USER_NAME = "admin";  
        private static final String PASSWORD = "123456";  
    
        /* 
         * 该方法是验证用户授权,根据用户名获取到他所拥有的角色以及权限,然后赋值到SimpleAuthorizationInfo对象中即可,Shiro就会按照我们配置的XX角色对应XX权限来进行判断     
        */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
            Set<String> roleNames = new HashSet<String>();  
            Set<String> permissions = new HashSet<String>();  
            roleNames.add("administrator");//添加角色
            permissions.add("newPage.jhtml");  //添加权限
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
            info.setStringPermissions(permissions);  
            return info;  
        }
    
    
        /* 
         *该方法是验证用户登录账户,在登录的时候需要将数据封装到Shiro的一个token中,执行shiro的login()方法,之后只要我们将MyShiroRealm这个类配置到Spring中,登录的时候Shiro就会自动的调用doGetAuthenticationInfo()方法进行验证
        */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(
                AuthenticationToken authcToken) throws AuthenticationException {
            UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
            if(token.getUsername().equals(USER_NAME)){
                return new SimpleAuthenticationInfo(USER_NAME, DecriptUtil.MD5(PASSWORD), getName());  
            }else{
                throw new AuthenticationException();  
            }
        }
             

    接下来是web.xml里面的配置,因为shiro是用拦截器来处理,所以你web.xml里面的shiro拦截器一定要写在其他拦截器里面,这样他能在你所有的url请求里面写执行,如果有的需要权限操作,没有权限直接返回,就不需要接下来的处理,会减少一些不必要的消耗

    <!-- 读取spring和shiro配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>
    </context-param>
    
    <!-- shiro过滤器 -->
    <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>*.jhtml</url-pattern>  
        <url-pattern>*.json</url-pattern>  
    </filter-mapping> 

    跟Spring结合的Spring-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"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans   
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"  
        default-lazy-init="true">  
    
        <description>Shiro Configuration</description>  
    
        <!-- Shiro's main business-tier object for web-enabled applications -->  
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
            <property name="realm" ref="myShiroRealm" />  
            <property name="cacheManager" ref="cacheManager" />  
        </bean>  
    
        <!-- 項目自定义的Realm -->  
        <bean id="myShiroRealm" class="com.luo.shiro.realm.MyShiroRealm">  
            <property name="cacheManager" ref="cacheManager" />  
        </bean>  
    
        <!-- Shiro Filter -->  
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
            <property name="securityManager" ref="securityManager" />  
            <property name="loginUrl" value="/login.jhtml" />  
            <property name="successUrl" value="/loginsuccess.jhtml" />  
            <property name="unauthorizedUrl" value="/error.jhtml" />  
            <property name="filterChainDefinitions">  
                <value>  
                    /index.jhtml = authc  
                    /login.jhtml = anon
                    /checkLogin.json = anon  
                    /loginsuccess.jhtml = anon  
                    /logout.json = anon  
                    /** = authc  
                </value>  
            </property>  
        </bean>  
    
        <!-- 用户授权信息Cache -->  
        <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  
    
        <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
    
        <!-- AOP式方法级权限检查 -->  
        <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
            depends-on="lifecycleBeanPostProcessor">  
            <property name="proxyTargetClass" value="true" />  
        </bean>  
    
        <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
            <property name="securityManager" ref="securityManager" />  
        </bean>  
    
    </beans>  
    这里有必要说清楚”shiroFilter” 这个bean里面的各个属性property的含义:
    
    (1)securityManager:这个属性是必须的,没什么好说的,就这样配置就好。
    (2)loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,可配置也可不配置。
    (3)successUrl:登录成功默认跳转页面,不配置则跳转至”/”,一般可以不配置,直接通过代码进行处理。
    (4)unauthorizedUrl:没有权限默认跳转的页面。
    (5)filterChainDefinitions,对于过滤器就有必要详细说明一下:
    
    1)Shiro验证URL时,URL匹配成功便不再继续匹配查找(所以要注意配置文件中的URL顺序,尤其在使用通配符时),故filterChainDefinitions的配置顺序为自上而下,以最上面的为准
    
    2)当运行一个Web应用程序时,Shiro将会创建一些有用的默认Filter实例,并自动地在[main]项中将它们置为可用自动地可用的默认的Filter实例是被DefaultFilter枚举类定义的,枚举的名称字段就是可供配置的名称
    
    3)通常可将这些过滤器分为两组:
    
    anon,authc,authcBasic,user是第一组认证过滤器
    
    perms,port,rest,roles,ssl是第二组授权过滤器
    
    注意user和authc不同:当应用开启了rememberMe时,用户下次访问时可以是一个user,但绝不会是authc,因为authc是需要重新认证的
    user表示用户不一定已通过认证,只要曾被Shiro记住过登录状态的用户就可以正常发起请求,比如rememberMe
    
    说白了,以前的一个用户登录时开启了rememberMe,然后他关闭浏览器,下次再访问时他就是一个user,而不会authc
    
    4)举几个例子
    /admin=authc,roles[admin] 表示用户必需已通过认证,并拥有admin角色才可以正常发起’/admin’请求
    /edit=authc,perms[admin:edit] 表示用户必需已通过认证,并拥有admin:edit权限才可以正常发起’/edit’请求
    /home=user 表示用户不一定需要已经通过认证,只需要曾经被Shiro记住过登录状态就可以正常发起’/home’请求
    
    5)各默认过滤器常用如下(注意URL Pattern里用到的是两颗星,这样才能实现任意层次的全匹配)
    /admins/**=anon 无参,表示可匿名使用,可以理解为匿名用户或游客
    /admins/user/**=authc 无参,表示需认证才能使用
    /admins/user/**=authcBasic 无参,表示httpBasic认证
    /admins/user/**=user 无参,表示必须存在用户,当登入操作时不做检查
    /admins/user/**=ssl 无参,表示安全的URL请求,协议为https
    /admins/user/*=perms[user:add:]
    参数可写多个,多参时必须加上引号,且参数之间用逗号分割,如/admins/user/*=perms[“user:add:,user:modify:*”]
    当有多个参数时必须每个参数都通过才算通过,相当于isPermitedAll()方法
    /admins/user/**=port[8081]
    当请求的URL端口不是8081时,跳转到schemal://serverName:8081?queryString
    其中schmal是协议http或https等,serverName是你访问的Host,8081是Port端口,queryString是你访问的URL里的?后面的参数
    /admins/user/**=rest[user]
    根据请求的方法,相当于/admins/user/**=perms[user:method],其中method为post,get,delete等
    /admins/user/**=roles[admin]
    参数可写多个,多个时必须加上引号,且参数之间用逗号分割,如/admins/user/**=roles[“admin,guest”]
    当有多个参数时必须每个参数都通过才算通过,相当于hasAllRoles()方法

    controller层代码,只是举例子,结合上面配置文件看

    package com.luo.controller;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.subject.Subject;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.alibaba.druid.support.json.JSONUtils;
    import com.luo.errorcode.LuoErrorCode;
    import com.luo.exception.BusinessException;
    import com.luo.util.DecriptUtil;
    
    @Controller
    public class UserController {
    
        @RequestMapping("/index.jhtml")
        public ModelAndView getIndex(HttpServletRequest request) throws Exception {
            ModelAndView mav = new ModelAndView("index");
            return mav;
        }
    
        @RequestMapping("/exceptionForPageJumps.jhtml")
        public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception {
            throw new BusinessException(LuoErrorCode.NULL_OBJ);
        }
    
        @RequestMapping(value="/businessException.json", method=RequestMethod.POST)
        @ResponseBody  
        public String businessException(HttpServletRequest request) {
            throw new BusinessException(LuoErrorCode.NULL_OBJ);
        }
    
        @RequestMapping(value="/otherException.json", method=RequestMethod.POST)
        @ResponseBody  
        public String otherException(HttpServletRequest request) throws Exception {
            throw new Exception();
        }
    
        //跳转到登录页面
        @RequestMapping("/login.jhtml")
        public ModelAndView login() throws Exception {
            ModelAndView mav = new ModelAndView("login");
            return mav;
        }
    
        //跳转到登录成功页面
        @RequestMapping("/loginsuccess.jhtml")
        public ModelAndView loginsuccess() throws Exception {
            ModelAndView mav = new ModelAndView("loginsuccess");
            return mav;
        }
    
        @RequestMapping("/newPage.jhtml")
        public ModelAndView newPage() throws Exception {
            ModelAndView mav = new ModelAndView("newPage");
            return mav;
        }
    
        @RequestMapping("/newPageNotAdd.jhtml")
        public ModelAndView newPageNotAdd() throws Exception {
            ModelAndView mav = new ModelAndView("newPageNotAdd");
            return mav;
        }
    
        /** 
         * 验证用户名和密码 
         * @param String username,String password
         * @return 
         */  
        @RequestMapping(value="/checkLogin.json",method=RequestMethod.POST)  
        @ResponseBody  
        public String checkLogin(String username,String password) {  
            Map<String, Object> result = new HashMap<String, Object>();
            try{
                UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtil.MD5(password));  
                Subject currentUser = SecurityUtils.getSubject();  
                if (!currentUser.isAuthenticated()){
                    //使用shiro来验证  
                    token.setRememberMe(true);  
                    currentUser.login(token);//验证角色和权限  
                } 
            }catch(Exception ex){
                throw new BusinessException(LuoErrorCode.LOGIN_VERIFY_FAILURE);
            }
            result.put("success", true);
            return JSONUtils.toJSONString(result);  
        }  
    
        /** 
         * 退出登录
         */  
        @RequestMapping(value="/logout.json",method=RequestMethod.POST)    
        @ResponseBody    
        public String logout() {   
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("success", true);
            Subject currentUser = SecurityUtils.getSubject();       
            currentUser.logout();    
            return JSONUtils.toJSONString(result);
        }  
    }

    整体大致思路就是这样

    感谢这两篇文章

    1:blog.csdn.net/u013142781/article/details/50629708

    2:www.jianshu.com/p/6786ddf54582

    不明白的看过上面两篇文章基本就差不多了,帅帅

  • 相关阅读:
    C# String.Format用法和格式说明
    VS2017桌面应用程序打包成.msi或者.exe
    Mysql授权允许远程访问
    C# Winform频繁刷新导致界面闪烁解决方法
    C# 解决窗体闪烁
    C# winform或控制台Properties.Settings.Default的使用及存储位置
    C# 获取计算机cpu,硬盘,内存相关的信息
    C# 多线程多文件批量下载---子线程中更新UI 实例
    Objective-C:NSSet和NSMutbaleSet的用法
    iOS:App上架流程和支付宝支付流程
  • 原文地址:https://www.cnblogs.com/hzzjj/p/7045816.html
Copyright © 2020-2023  润新知