Shiro授权&&Shiro的注解式开发

发布于:2023-01-04 ⋅ 阅读:(369) ⋅ 点赞:(0)

目录

一、Shiro授权

        1.1 权限设计的五张表

        1.2 实现授权的步骤

                1.2.1 编写Mapper层、service层

                1.2.2 编写自定义Realm中的授权方法

                1.2.3 测试

二、Shiro注解式开发

        2.1 常用注解介绍

        2.2 编写Controller层

        2.3 在springmvc.xml中配置拦截器

        2.4 前端测试页面

        2.5 测试


一、Shiro授权

        1.1 权限设计的五张表

授角色:用户具备哪些角色?

授权限:用户具备哪些权限?

我们带着问题来看看权限设计的这五张表:

用户表、用户角色表、角色表、角色权限表、权限表(五张表)

        1.1.1 编写SQL语句

-- 授角色:用户具备哪些角色?
select roleid from t_shiro_user u,t_shiro_user_role ur
where u.userid = ur.userid and u.username = 'zdm'

-- 授权限:用户具备哪些权限?
select rp.perid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp 
where u.userid = ur.userid and ur.roleid = rp.roleid and u.username = 'ls'

        1.2 实现授权的步骤

                1.2.1 编写Mapper层、service层

① 在UserMapper.xml中添加两个SQL配置

<!-- 查询角色ID -->
<select id="selectRoleIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
  select roleid from t_shiro_user u,t_shiro_user_role ur
  where u.userid = ur.userid and u.username = #{userName}
</select>

<!-- 查询权限ID -->
<select id="selectPerIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
  select rp.perid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp
  where u.userid = ur.userid and ur.roleid = rp.roleid and u.username = #{userName}
</select>

② 在Mapper层、Biz层、UserBizImpl实现类里面也添加上这两个方法

UserMapper

package com.leaf.ssm.mapper;

import com.leaf.ssm.model.User;
import javafx.scene.effect.SepiaTone;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.Set;

@Repository
public interface UserMapper {
    int deleteByPrimaryKey(Integer userid);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userid);

    //通过账户名查询用户信息
    User queryUserByUserName(@Param("userName") String userName);

    //通过账号名查询对应的角色
    Set<String> selectRoleIdsByUserName(@Param("userName") String userName);

    //通过账户名查询对应的权限
    Set<String> selectPerIdsByUserName(@Param("userName") String userName);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

 UserBiz

package com.leaf.ssm.biz;

import com.leaf.ssm.model.User;
import org.apache.ibatis.annotations.Param;

import java.util.Set;

public interface UserBiz {
    int deleteByPrimaryKey(Integer userid);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userid);

    //通过用户名查询出用户信息
    User queryUserByUserName(String userName);

    //通过账号名查询对应的角色
    Set<String> selectRoleIdsByUserName(String userName);

    //通过账户名查询对应的权限
    Set<String> selectPerIdsByUserName(String userName);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

}

UserBizImpl

package com.leaf.ssm.biz.impl;

import com.leaf.ssm.biz.UserBiz;
import com.leaf.ssm.mapper.UserMapper;
import com.leaf.ssm.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author Leaf
 * @site 2977819715
 * @company 玉渊工作室
 * @create  2022-08-26 3:29
 */
//交给spring进行管理并且指定类名
@Service("userBiz")
public class UserBizImpl implements UserBiz {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int deleteByPrimaryKey(Integer userid) {
        return userMapper.deleteByPrimaryKey(userid);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Integer userid) {
        return userMapper.selectByPrimaryKey(userid);
    }

    @Override
    public User queryUserByUserName(String userName) {
        return userMapper.queryUserByUserName(userName);
    }

    @Override
    public Set<String> selectRoleIdsByUserName(String userName) {
        return userMapper.selectRoleIdsByUserName(userName);
    }

    @Override
    public Set<String> selectPerIdsByUserName(String userName) {
        return userMapper.selectPerIdsByUserName(userName);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }
}

                1.2.2 编写自定义Realm中的授权方法

③ 编写自定义Realm中的授权方法

MyRealm

package com.leaf.ssm.shiro;

import com.leaf.ssm.biz.UserBiz;
import com.leaf.ssm.model.User;
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 org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author Leaf
 * @site 2977819715
 * @company 玉渊工作室
 * @create  2022-08-26 3:37
 */
public class MyRealm extends AuthorizingRealm {

    public UserBiz userBiz;

    public UserBiz getUserBiz() {
        return userBiz;
    }

    public void setUserBiz(UserBiz userBiz) {
        this.userBiz = userBiz;
    }

    /**
     * 授权
     * @param principals
     * @return
     * 替代了昨天的shiro-web.ini
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //拿到账户名
        String userName = principals.getPrimaryPrincipal().toString();
        //调用查询用户角色&&权限的方法
        Set<String> roleIds = userBiz.selectRoleIdsByUserName(userName);
        Set<String> perIds = userBiz.selectPerIdsByUserName(userName);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将当前登录的权限交给shiro的授权器
        info.setStringPermissions(perIds);
        //将当前登录的角色交给shiro的授权器
        info.setRoles(roleIds);
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     * 替代了昨天的shiro.ini
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //拿到用户名
        String userName = token.getPrincipal().toString();
        //根据用户名查询到用户对象
        User user = userBiz.queryUserByUserName(userName);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName() // realm的名字
        );
        return info;
    }
}

我们在shiro的配置文件中添加指定的角色和权限信息,配合测试:

<!-- 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[4]
        /user/teacher.jsp=perms[2]
        <!-- /css/**               = anon
         /images/**            = anon
         /js/**                = anon
         /                     = anon
         /user/logout          = logout
         /user/**              = anon
         /userInfo/**          = authc
         /dict/**              = authc
         /console/**           = roles[admin]
         /**                   = anon-->
    </value>
</property>

                1.2.3 测试

        使用zs登录

 

访问只有zdm才可以访问的页面addUser.jsp

更换为zdm进行登录

然后我们再次访问addUser.jsp

这就代表我们的授权功能编写成功,测试完毕。


二、Shiro注解式开发

        2.1 常用注解介绍

@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true

@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份

身份认证 @RequiresUser:表示当前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

        2.2 编写Controller层

        ShiroController

package com.leaf.ssm.controller;

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.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Leaf
 * @site 2977819715
 * @company 玉渊工作室
 * @create  2022-08-28 19:15
 */
@RequestMapping("/shiro")
@Controller
public class ShiroController {

    //@RequiresUser等价于 spring-shiro.xml 中的/user/updatePwd.jsp=authc
    //@RequiresUser代表当前方法只有登录后才能够访问
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(){
        System.out.println("身份认证通过");
        return "admin/addUser";
    }

    //@RequiresRoles 当前方法只有 具备指定的角色 才能访问
    //@RequiresRoles 等价于 spring-shiro.xml 中的/admin/*.jsp=roles[4]配置
    @RequiresRoles(value = {"1","4"},logical = Logical.OR)
    @RequestMapping("/passRole")
    public String passRole(){
        System.out.println("角色认证通过");
        return "admin/addUser";
    }

    //@RequiresPermissions 当前方法只有 具备指定的权限 才能访问
    //@RequiresPermissions 等价于 spring-shiro.xml 中的/user/teacher.jsp=perms[2]配置
    @RequiresPermissions(value = {"2"},logical = Logical.AND)
    @RequestMapping("/passPermission")
    public String passPermission(){
        System.out.println("权限认证通过");
        return "admin/addUser";
    }

}

        2.3 在springmvc.xml中配置拦截器

        springmvc.xml

    <!-- 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>

    <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>

        2.4 前端测试页面

放上一个测试页面,方便测试不同用户访问不同的页面;

TestShiro.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/28
  Time: 19:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<ul>
    shiro注解
    <li>
        <a href="${pageContext.request.contextPath}/shiro/passUser">用户认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/shiro/passRole">角色</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/shiro/passPermission">权限认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/logout">退出系统</a>
    </li>
</ul>
</body>
</html>

        2.5 测试

我们通过登录不同的角色用户来测试我们的注解式授权开发是否成功;

用zs登录:

验证权限:

利用zdm登录:

验证权限:

到这里也就证明我们的注解式开发实现授权成功,测试完毕。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到