shiro实现登录安全认证(转)

shiro实现登录安全认证

shiro的优势,不需要再代码里面判断是否登录,是否有执行的权限,实现了从前端页面到后台代码的权限的控制非常的灵活方便

传统的登录认证方式是,从前端页面获取到用户输入的账号和密码之后,直接去数据库查询账号和密码是否匹配和存在,如果匹配和存在就登录成功,没有就提示错误

而shiro的认证方式则是,从前端页面获取到用户输入的账号和密码之后,传入给一个UsernamePasswordToken对象也就是令牌,

然后再把令牌传给subject,subject会调用自定义的 realm,

realm做的事情就是用前端用户输入的用户名,去数据库查询出一条记录(只用用户名去查,查询拿到返回用户名和密码),然后再把两个密码进行对比,不一致就跑出异常

也就是说如果subject.login(token);没有抛出异常,就表示用户名和密码是匹配的,表示登录成功

1.在pom.xml中引入shiro依赖

    <!-- 引入shiro框架的依赖 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.2.2</version>
        </dependency>

2.在web.xml中配置过滤器

<!-- 配置spring提供的用于整合shiro框架的过滤器 -->
  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

3.在applicationContext.xml中配置DelegatingFilterProxy的Bean

<!-- 配置一个shiro框架的过滤器工厂bean,用于创建shiro框架的过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 注入安全管理器对象 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 注入登录页面访问URL -->
        <property name="loginUrl" value="/login.jsp"/>
        <!-- 注入权限不足提供页面访问URL -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/><!-- 已经登录,但是用户没有权限的时候才跳转 -->
        <!-- 配置URL拦截规则 -->
        <property name="filterChainDefinitions">
            <value>
                /css/** = anon
                /js/** = anon
                /images/** = anon
                /validatecode.jsp* = anon
                /login.jsp* = anon
                /userAction_login.action = anon
                /page_base_staff.action = perms["staff"]
                /** = authc<!-- 其他设置用户认证才能使用-->
            </value>
        </property>
    </bean>
<span class="co"><span class="hljs-comment">&lt;!-- 注册安全管理器 --&gt;</span></span>
<span class="kw"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span></span></span><span class="ot"><span class="hljs-tag"> <span class="hljs-attr">id</span>=</span></span><span class="st"><span class="hljs-tag"><span class="hljs-string">"securityManager"</span></span></span><span class="ot"><span class="hljs-tag"> <span class="hljs-attr">class</span>=</span></span><span class="st"><span class="hljs-tag"><span class="hljs-string">"org.apache.shiro.web.mgt.DefaultWebSecurityManager"</span></span></span><span class="kw"><span class="hljs-tag">&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></span></code></pre></div>

常用过滤器

常用过滤器:
anon:例子/admins/**=anon表示可以匿名访问
authc:例如/admins/user/**=authc表示需要认证才能使用,没有参数
perms:例子/page_base_staff.action = perms["staff"],当前用户需要有staff权限才可以访问。
roles:例子/admins/user/**=roles[admin],当前用户是否有这个角色权限。

登录方法的编写

传统的登录方法

    
    public String login(){
                //调用service层查询账号和密码是否一致
                UserBean user= userService.login(model);
                if(user!=null)
                {
                    return "index";
                }
                else
                {
                    addActionError("用户名和密码不匹配...");
                    return "login";
                }
        }
}</code></pre></div>

shiro的登录认证方法

    public String login(){           
                if((!StringUtils.isBlank(checkcode))&&key.contentEquals(checkcode) )
                {
                    Subject subject = SecurityUtils.getSubject();//获取当前用户对象
                    //生成令牌(传入用户输入的账号和密码)
                    UsernamePasswordToken token=new UsernamePasswordToken(model.getUsername(),MD5Utils.md5(model.getPassword()));
                <span class="co"><span class="hljs-comment">//认证登录</span></span>
                <span class="kw"><span class="hljs-keyword">try</span></span> {
                    <span class="co"><span class="hljs-comment">//这里会加载自定义的realm</span></span>
            subject.<span class="fu">login</span>(token);<span class="co"><span class="hljs-comment">//把令牌放到login里面进行查询,如果查询账号和密码时候匹配,如果匹配就把user对象获取出来,失败就抛异常</span></span>
            UserBean user= (UserBean) subject.<span class="fu">getPrincipal</span>();<span class="co"><span class="hljs-comment">//获取登录成功的用户对象(以前是直接去service里面查)</span></span>
            ServletActionContext.<span class="fu">getRequest</span>().<span class="fu">getSession</span>().<span class="fu">setAttribute</span>(<span class="st"><span class="hljs-string">"user"</span></span>, user);
                    <span class="kw"><span class="hljs-keyword">return</span></span> <span class="st"><span class="hljs-string">"index"</span></span>;
                } <span class="kw"><span class="hljs-keyword">catch</span></span> (Exception e) {
                    <span class="co"><span class="hljs-comment">//认证登录失败抛出异常</span></span>
                    <span class="fu">addActionError</span>(<span class="st"><span class="hljs-string">"用户名和密码不匹配..."</span></span>);
                    <span class="kw"><span class="hljs-keyword">return</span></span> <span class="st"><span class="hljs-string">"login"</span></span>;
                }
            }
    }


                </code></pre></div>

自定义realm的编写

public class Bos_realm extends AuthorizingRealm {
<span class="fu"><span class="hljs-meta">@Resource</span></span>
<span class="kw"><span class="hljs-keyword">private</span></span> IUserDao&lt;UserBean&gt; userDao;
<span class="co"><span class="hljs-comment">//授权</span></span>
<span class="fu"><span class="hljs-meta">@Override</span></span>
<span class="kw"><span class="hljs-function"><span class="hljs-keyword">protected</span></span></span><span class="hljs-function"> AuthorizationInfo </span><span class="fu"><span class="hljs-function"><span class="hljs-title">doGetAuthorizationInfo</span></span></span><span class="hljs-function"><span class="hljs-params">(PrincipalCollection arg0)</span> </span>{
    <span class="co"><span class="hljs-comment">// TODO Auto-generated method stub</span></span>
    <span class="kw"><span class="hljs-keyword">return</span></span> <span class="kw"><span class="hljs-keyword">null</span></span>;
}

<span class="co"><span class="hljs-comment">//认证</span></span>
<span class="fu"><span class="hljs-meta">@Override</span></span>
<span class="kw"><span class="hljs-function"><span class="hljs-keyword">protected</span></span></span><span class="hljs-function"> AuthenticationInfo </span><span class="fu"><span class="hljs-function"><span class="hljs-title">doGetAuthenticationInfo</span></span></span><span class="hljs-function"><span class="hljs-params">(AuthenticationToken token)</span> </span><span class="kw"><span class="hljs-function"><span class="hljs-keyword">throws</span></span></span><span class="hljs-function"> AuthenticationException </span>{
    
UsernamePasswordToken usertoken=(UsernamePasswordToken) token;<span class="co"><span class="hljs-comment">//获取令牌(里面存放new UsernamePasswordToken放入的账号和密码)</span></span>
  
    <span class="co"><span class="hljs-comment">//得到账号和密码</span></span>
    String username = usertoken.<span class="fu">getUsername</span>();
    
    UserBean findusername = userDao.<span class="fu">findByusername</span>(username);<span class="co"><span class="hljs-comment">//去sql查询用户名是否存在,如果存在返回对象(账号和密码都有的对象)</span></span>
  
    <span class="kw"><span class="hljs-keyword">if</span></span>(findusername!=<span class="kw"><span class="hljs-keyword">null</span></span>)<span class="co"><span class="hljs-comment">//如果用户名存在</span></span>
    {
        <span class="co"><span class="hljs-comment">//参数1.用户认证的对象(subject.getPrincipal();返回的对象),</span></span>
        <span class="co"><span class="hljs-comment">//参数2.从数据库根据用户名查询到的用户的密码</span></span>
        <span class="co"><span class="hljs-comment">//参数3.把当前自定义的realm对象传给SimpleAuthenticationInfo,在配置文件需要注入</span></span>
        AuthenticationInfo Info = <span class="kw"><span class="hljs-keyword">new</span></span> <span class="fu">SimpleAuthenticationInfo</span>(findusername, findusername.<span class="fu">getPassword</span>(),<span class="kw"><span class="hljs-keyword">this</span></span>.<span class="fu">getName</span>());
        <span class="kw"><span class="hljs-keyword">return</span></span> Info;
    
    }<span class="kw"><span class="hljs-keyword">else</span></span>
    {
        <span class="kw"><span class="hljs-keyword">return</span></span> <span class="kw"><span class="hljs-keyword">null</span></span>;
    }
}

}

在安全管理器里面注入自定义的realm

    <!-- 注册安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- 注入realm到安全管理器进行密码匹配 -->
    <property name="realm" ref="BosRealm"></property>
    </bean>
    <!-- 自定义的realm -->
    <bean id="BosRealm" class="com.itheima.bos.action.Bos_realm"></bean>

添加权限四方式

1_url

在里面添加拦截规则

<!-- 配置URL拦截规则 -->
        <property name="filterChainDefinitions">
            <value>
                /css/** = anon
                /js/** = anon
                /images/** = anon
                /validatecode.jsp* = anon
                /login.jsp* = anon
                /User_login.action= anon
                /page_base_staff.action = perms["staff"] <!-- 拦截page_base_staff.action这个方法必须有staff权限才能使用 -->
                /** = authc
            </value>
        </property>

2_注解

需要在中配置开启注解扫描才能使用

开启添加权限的注解扫描

    <bean id="defaultAdvisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
        <!-- 配置强制使用cglib方式为Action创建代理对象 -->
        <property name="proxyTargetClass" value="true"/>
    </bean>
<span class="co"><span class="hljs-comment">&lt;!-- 配置shiro框架的切面类 --&gt;</span></span>
<span class="kw"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span></span></span><span class="ot"><span class="hljs-tag"> <span class="hljs-attr">class</span>=</span></span><span class="st"><span class="hljs-tag"><span class="hljs-string">"org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"</span></span></span><span class="kw"><span class="hljs-tag">/&gt;</span></span></code></pre></div>
//把订单设置为作废
    @RequiresPermissions("staff.delete")//为delete这个方法添加staff.delete权限
    public String delete()
    {
        //得到id
        staffService.deleteBatch(ids);
        return "staff";
    }

3_jsp页面

需要导入shiro标签库

<%@ taglib uri="http://shiro.apache.org/tags"  prefix="shiro"%>
    /* 有staff权限才能显示此按钮 */
<shiro:hasPermission name="staff1">
    {
        id : 'button-delete',
        text : '作废',
        iconCls : 'icon-cancel',
        handler : doDelete
    },
    </shiro:hasPermission>

4_代码(几乎不用)

在要设置权限的代码中添加一下两行代码就可以了

    //修改
    public String edit()
    {
        Subject subject = SecurityUtils.getSubject();
        subject.checkPermission("staff.edit");//要运行此方法下面的代码,必须要拥有staff.edit的权限
        //更新model
        staffService.update(model);
        return "staff";
    }

授权

手动授权和认证

因为要授权的权限太多,所以需要一张权限表

public class Bos_realm extends AuthorizingRealm {
<span class="fu"><span class="hljs-meta">@Resource</span></span>
<span class="kw"><span class="hljs-keyword">private</span></span> IUserDao&lt;UserBean&gt; userDao;
<span class="co"><span class="hljs-comment">//授权</span></span>
<span class="fu"><span class="hljs-meta">@Override</span></span>
<span class="kw"><span class="hljs-function"><span class="hljs-keyword">protected</span></span></span><span class="hljs-function"> AuthorizationInfo </span><span class="fu"><span class="hljs-function"><span class="hljs-title">doGetAuthorizationInfo</span></span></span><span class="hljs-function"><span class="hljs-params">(PrincipalCollection arg0)</span> </span>{

  
    SimpleAuthorizationInfo info = <span class="kw"><span class="hljs-keyword">new</span></span> <span class="fu">SimpleAuthorizationInfo</span>();
    info.<span class="fu">addStringPermission</span>(<span class="st"><span class="hljs-string">"staff"</span></span>);<span class="co"><span class="hljs-comment">//为page_base_staff.action请求授权staff权限</span></span>
    info.<span class="fu">addStringPermission</span>(<span class="st"><span class="hljs-string">"staff.delete"</span></span>);<span class="co"><span class="hljs-comment">//为page_base_staff.action请求授权staff权限</span></span>
    info.<span class="fu">addStringPermission</span>(<span class="st"><span class="hljs-string">"staff.edit"</span></span>);
    <span class="kw"><span class="hljs-keyword">return</span></span> info;
 
}

<span class="co"><span class="hljs-comment">//用户的登录认证</span></span>
<span class="fu"><span class="hljs-meta">@Override</span></span>
<span class="kw"><span class="hljs-function"><span class="hljs-keyword">protected</span></span></span><span class="hljs-function"> AuthenticationInfo </span><span class="fu"><span class="hljs-function"><span class="hljs-title">doGetAuthenticationInfo</span></span></span><span class="hljs-function"><span class="hljs-params">(AuthenticationToken token)</span> </span><span class="kw"><span class="hljs-function"><span class="hljs-keyword">throws</span></span></span><span class="hljs-function"> AuthenticationException </span>{
    <span class="co"><span class="hljs-comment">//这里添加认证代码</span></span>
  
  UsernamePasswordToken usertoken=(UsernamePasswordToken) token;<span class="co"><span class="hljs-comment">//获取令牌(里面存放的有账号和密码)</span></span>
    
    <span class="co"><span class="hljs-comment">//查询用户名是否存在</span></span>
    String username = usertoken.<span class="fu">getUsername</span>();
    
    UserBean findusername = userDao.<span class="fu">findByusername</span>(username);<span class="co"><span class="hljs-comment">//去sql查询用户名是否存在</span></span>
    <span class="kw"><span class="hljs-keyword">if</span></span>(findusername!=<span class="kw"><span class="hljs-keyword">null</span></span>)<span class="co"><span class="hljs-comment">//如果用户名存在</span></span>
    {
        <span class="co"><span class="hljs-comment">//参数1.用户认证的对象(subject.getPrincipal();返回的对象),</span></span>
        <span class="co"><span class="hljs-comment">//参数2.从数据库根据用户名查询到的用户的密码</span></span>
        <span class="co"><span class="hljs-comment">//参数3.把当前自定义的realm对象传给SimpleAuthenticationInfo,在配置文件需要注入</span></span>
        AuthenticationInfo Info = <span class="kw"><span class="hljs-keyword">new</span></span> <span class="fu">SimpleAuthenticationInfo</span>(findusername, findusername.<span class="fu">getPassword</span>(),<span class="kw"><span class="hljs-keyword">this</span></span>.<span class="fu">getName</span>());
        <span class="kw"><span class="hljs-keyword">return</span></span> Info;
    
    }<span class="kw"><span class="hljs-keyword">else</span></span>
    {
        <span class="kw"><span class="hljs-keyword">return</span></span> <span class="kw"><span class="hljs-keyword">null</span></span>;
    }

}

遍历数据库授权

获取当前登录的用户,去数据库查询当前用户的所有权限,然后添加

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();       
    <span class="co"><span class="hljs-comment">//获取当前用户</span></span>
    UserBean findusername = session.<span class="fu">get</span>......;
    
    <span class="co"><span class="hljs-comment">//结果集</span></span>
    List&lt;AuthFunction&gt; functionList =<span class="kw"><span class="hljs-keyword">null</span></span>;

    <span class="co"><span class="hljs-comment">//去sql查询当前用户的权限</span></span>
    <span class="kw"><span class="hljs-keyword">if</span></span>(<span class="st"><span class="hljs-string">"admin"</span></span>.<span class="fu">equals</span>(findusername.<span class="fu">getUsername</span>()))<span class="co"><span class="hljs-comment">//如果是管理员,获取所有权限</span></span>
    {
         functionList = functionDao.<span class="fu">findAll</span>();
    }<span class="kw"><span class="hljs-keyword">else</span></span>
    {
        String hql = <span class="st"><span class="hljs-string">"SELECT DISTINCT f FROM AuthFunction f LEFT OUTER JOIN f.authRoles r LEFT              OUTER JOIN r.userBeans u WHERE u.id = ?"</span></span>;
        functionList = functionDao.<span class="fu">findByHQL</span>(hql,findusername.<span class="fu">getId</span>());
    }
    
    <span class="co"><span class="hljs-comment">//遍历结果集授权</span></span>
    <span class="kw"><span class="hljs-keyword">for</span></span> (AuthFunction authFunction : functionList) {
        info.<span class="fu">addStringPermission</span>(authFunction.<span class="fu">getCode</span>());
    }

    <span class="kw"><span class="hljs-keyword">return</span></span> info;</code></pre></div>
posted @ 2018-01-26 10:36  星朝  阅读(677)  评论(0编辑  收藏  举报