Shiro授权-SSM

前言:

根据我们之前所讲的shiro认证-SSM里面的知识,我们实现了身份的验证登录,接下来我们所要实现的是我们的角色和权限的授权方法。用到的依然是我们上次所需要的数据库。

首先我们看一下数据库的表的权限设计图设计:
在这里插入图片描述
shiro授权角色、权限
1.添加角色和权限的授权方法

//根据username查询该用户的所有角色,用于角色验证
Set findRoles(String username);

//根据username查询他所拥有的权限信息,用于权限判断
Set findPermissions(String username);

2.自定义Realm配置Shiro授权认证

  1. 获取验证身份(用户名)
  2. 根据身份(用户名)获取角色和权限信息
  3. 将角色和权限信息设置到SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
    info.setRoles(roles);
    info.setStringPermissions(permissions);

既然我们需要进行权限认证,首先我们需要根据用户id获取他的角色id(role)和权限(pers),所以需要在ShiroUserMapper写两个查询的方法。
我们这里用的是set集合,因为我们可以获取到多个角色以及多个权限,如果我们查询出来的角色和对应的权限有重复的话,那么set集合可以帮我们把重复的去除掉,以达到去重的目的

在这里插入图片描述
ShiroUserMapper

 /**
     * 查询角色id
     * @param userid
     * @return
     */
    Set<String> getRolesByUserId(@Param("userid") Integer userid);

    /**
     * 查询权限id
     * @param userid
     * @return
     */
    Set<String> getPersByUserId(@Param("userid") Integer userid);

ShiroUserMapper.xml
在这里插入图片描述

 <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
    where u.userid = ur.userid and ur.roleid = r.roleid
    and u.userid = #{userid}
</select>

  <select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
  where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
  and u.userid = #{userid}
</select>

MyRealm
代码如下:

package com.dengrenli.shiro;

import com.dengrenli.model.ShiroUser;
import com.dengrenli.service.ShiroUserService;
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;

import java.util.Set;

/**
 * @author小科比
 * @site www.dengrenli.com
 * @company 科比公司
 * @create  2019-11-03 19:56
 * 这个类就替换掉了我们之前写的.ini文件,所有用户的身份都从这里来
 */
public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }
    /**
     * 授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //从这principalCollection里面拿到要授权的账号
        //getPrimaryPrincipal()这个是唯一的身份
        String uname=principalCollection.getPrimaryPrincipal().toString();
        //拿到当前的用户
        ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
        //拿到当前userid对应所有权限
        Set<String> perids= this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        //对应的所有角色
        Set<String> roleIds= this.shiroUserService.getRolesByUserId(shiroUser.getUserid());

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //设置角色
        info.setRoles(roleIds);
        //设置权限
        info.setStringPermissions(perids);
        //返回AuthorizationInfo
        return info;
    }


    /**
     * 身份验证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname = authenticationToken.getPrincipal().toString();
        String pwd = authenticationToken.getCredentials().toString();
        ShiroUser shiroUser = shiroUserService.queryByName(uname);

        //将数据库中的数据和前台(token)
        //传入的数据放入到SimpleAuthenticationInfo,
        ///验证的任务是交给shiro去做的
        AuthenticationInfo info=new SimpleAuthenticationInfo(
                shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                //this.getName()指的就是MyRealm这个类的类名
                this.getName()
        );
        //返回 AuthenticationInfo
        return info;
    }
}

applicationCatext-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.xsd">

    <!--配置自定义的Realm-->
    <bean id="shiroRealm" class="com.dengrenli.shiro.MyRealm">
        <property name="shiroUserService" ref="shiroUserService" />
        <!--注意:重要的事情说三次~~~~~~此处解密方式要与用户注册时的加密算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处解密方式要与用户注册时的加密算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处解密方式要与用户注册时的加密算法一致 -->
        <!--以下三个配置告诉shiro将如何对用户传来的明文密码进行解密-->
        <property name="credentialsMatcher">
            <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--指定hash算法为MD5-->
                <property name="hashAlgorithmName" value="md5"/>
                <!--指定散列次数为1024次-->
                <property name="hashIterations" value="1024"/>
                <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储-->
                <property name="storedCredentialsHexEncoded" value="true"/>
            </bean>
        </property>
    </bean>

    <!--注册安全管理器-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="shiroRealm" />
    </bean>

    <!--Shiro核心过滤器-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 身份验证失败,跳转到登录页面 -->
        <property name="loginUrl" value="/login"/>
        <!-- 身份验证成功,跳转到指定页面 -->
        <!--<property name="successUrl" value="/index.jsp"/>-->
        <!-- 权限验证失败,跳转到指定页面 -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                <!--
                注:anon,authcBasic,auchc,user是认证过滤器
                    perms,roles,ssl,rest,port是授权过滤器
                -->
                <!--anon 表示匿名访问,不需要认证以及授权-->
                <!--authc表示需要认证 没有进行身份认证是不能进行访问的-->
                <!--roles[admin]表示角色认证,必须是拥有admin角色的用户才行-->
                /user/login=anon
                /user/updatePwd.jsp=authc
                /admin/*.jsp=roles[admin]
                /user/teacher.jsp=perms["user:update"]
                <!-- /css/**               = anon
                 /images/**            = anon
                 /js/**                = anon
                 /                     = anon
                 /user/logout          = logout
                 /user/**              = anon
                 /userInfo/**          = authc
                 /dict/**              = authc
                 /console/**           = roles[admin]
                 /**                   = anon-->
            </value>
        </property>
    </bean>

    <!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>

在这里插入图片描述
在我们Shiro入门阶段里面我们的用户和角色还有角色对应的权限是写死在.ini文件里面的,我们现在是要在数据库里面拿数据,然后找到用户对应的角色和权限,Shiro是一个框架,所以我们只要满足它所定义的规则,然后框架就可以帮我们实现对应的功能,所以我们只需要将角色和权限信息设置到SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();里面就可以了,然后我们每次点击菜单项,然后已经是认证登录进来的,它就会只进行doGetAuthorizationInfo的授权方法,最终校验的规则是在applicationCatext-shiro.xml里面(如上图所示)根据这个规则执行相应的权限操作,但如果你没进行认证登录,你是直接访问主界面,你点击菜单项的时候,他就会先进行doGetAuthenticationInfo身份验证的方法,当然肯定是认证失败的,所以会执行用户认证失败的操作

注解式开发

4.配置注解权限验证

4.1 Shiro注解

@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
@RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
@RequiresRoles(value = {“admin”,“user”},logical = Logical.AND):表示当前Subject需要角色admin和user
@RequiresPermissions(value = {“user:delete”,“user:b”},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b

4.2 开启注解

注:
必须将Shiro注解的开启放置到spring-mvc.xml中(即放在springMVC容器中加载),不然Shiro注解开启无效!!!

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
      depends-on="lifecycleBeanPostProcessor">
    <property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

4.3 注解权限验证失败不跳转路径问题

问题原因:由于我们架构是用springmvc框架来搭建的所以项目的路径跳转是由springmvc 来控制的,也就是说我们在shiro里面的配置没有用

  <!-- 身份验证成功,跳转到指定页面 -->
  <property name="successUrl" value="/index.jsp"/>                //没有用,达不到预期效果
  <!-- 权限验证失败,跳转到指定页面 -->
  <property name="unauthorizedUrl" value="/user/noauthorizeUrl"/> //没有用,达不到预期效果

解决方案:
springmvc中有一个org.springframework.web.servlet.handler.SimpleMappingExceptionResolver类就可以解决这个问题

 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="org.apache.shiro.authz.UnauthorizedException">
                unauthorized
            </prop>
        </props>
    </property>
	<property name="defaultErrorView" value="unauthorized"/>
  </bean>

在这里插入图片描述
测试
在这里插入图片描述

<ul>
    shiro注解
    <li>
        <a href="${pageContext.request.contextPath}/passUser">用户认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passRole">角色</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passPer">权限认证</a>
    </li>
</ul>

然后我们通过ShiroUserController类来讲就是这些注解:

代码如下:

  package com.dengrenli.controller;

import com.dengrenli.model.ShiroUser;
import com.dengrenli.service.ShiroUserService;
import com.dengrenli.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author小科比
 * @site www.dengrenli.com
 * @company 科比公司
 * @create  2019-11-04 05:59
 */
@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    /*
    登录方法
     */
    @RequestMapping("/login")
    public  String login(HttpServletRequest req) {
        Subject subject = SecurityUtils.getSubject();
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd);
        try {
            //这里还跳转到MyRealm中的认证方法
           subject.login(token);
           req.getSession().setAttribute("username",uname);
          return "main";
        } catch (Exception e) {
          req.setAttribute("message","用户名密码错误");
          return "login";
        }
    }
    @RequestMapping("/logout")
    public  String logout(HttpServletRequest req) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    /**
     * 用户注册
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("/register")
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        String salt = PasswordHelper.createSalt();
        String credentials = PasswordHelper.createCredentials(pwd, salt);

        ShiroUser shiroUser=new ShiroUser();
        shiroUser.setUsername(uname);
        shiroUser.setPassword(credentials);
        shiroUser.setSalt(salt);
        int insert = shiroUserService.insert(shiroUser);
        if(insert>0){
            req.setAttribute("message","注册成功");
            return "login";
        }
        else{
            req.setAttribute("message","注册失败");
            return "register";
        }
    }

    @RequiresUser
    @ResponseBody
    @RequestMapping("/passUser")
    public  String passUser(){

        return "身份认证成功,能够访问!!!";
    }

    //value = {"2"}这个2是角色id为2的意思,
    // value = {"2","3"} 意思是 一个用户同时拥有2这个角色和3这个角色,
    // AND的意思是同时拥有
    //OR 的意思是 或
    @RequiresRoles(value = {"2","3"},logical= Logical.OR)
    @ResponseBody
    @RequestMapping("/passRole")
    public  String passRole(){

        return "角色认证成功,能够访问!!!";
    }

    @RequiresPermissions(value = {"user:update","user:load"},logical= Logical.AND)
    @ResponseBody
    @RequestMapping("/passPer")
    public  String passPer(){

        return "权限认证成功,能够访问!!!";
    }


}


效果和我们之前的权限实现效果是一样,这里就不一一演示了。
谢谢大家,多多指教!!!
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值