• shiro授权、注解式开发


    Shiro授权

    流程:根据前台传递管理的账号和密码进行认真,在跳页面前进行授权验证,看这个用户是否有这个权限。

    今天的权限是由5张表构成的:

    写两个查询方法:

     <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 = #{uid}
    </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 = #{uid}
    </select>

    ShourUserMapper

        Set<String> getRolesByUserId(Integer uid);
    
        Set<String> getPersByUserId(Integer uid);

    ShourUserService

    package com.cjh.service;
    
    import com.cjh.model.ShiroUser;
    
    import java.util.Set;
    
    /**
     * @author
     * @site
     * @company
     * @create 2019-10-13 16:29
     */
    public interface ShiroUserService {
        /**
         * 用于shiro认证
         * @param uname
         * @return
         */
        public ShiroUser queryByName(String uname);
    
        int insert(ShiroUser record);
    
        Set<String> getRolesByUserId(Integer uid);
    
        Set<String> getPersByUserId(Integer uid);
    }

    ShourUserServiceimpl

    package com.cjh.service.Impl;
    
    import com.cjh.mapper.ShiroUserMapper;
    import com.cjh.model.ShiroUser;
    import com.cjh.service.ShiroUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Set;
    
    /**
     * @author
     * @site
     * @company
     * @create 2019-10-13 16:31
     */
    @Service("shiroUserService")
    public class ShiroUserServiceImpl implements ShiroUserService {
        @Autowired
        private ShiroUserMapper shiroUserMapper;
        @Override
        public ShiroUser queryByName(String uname) {
            return shiroUserMapper.queryByName(uname);
        }
    
        @Override
        public int insert(ShiroUser record) {
            return shiroUserMapper.insert(record);
        }
    
        @Override
        public Set<String> getRolesByUserId(Integer uid) {
            return shiroUserMapper.getRolesByUserId(uid);
        }
    
        @Override
        public Set<String> getPersByUserId(Integer uid) {
            return shiroUserMapper.getPersByUserId(uid);
        }
    
    
    }

    MyRealm

    package com.cjh.shiro;
    
    import com.cjh.model.ShiroUser;
    import com.cjh.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
     * @company
     * @create 2019-10-13 16:19
     * 认证过程
     * 1.数据原(ini-》数据库)
     * 2.doGetAuthenticationInfo将数据库的用户信息个shbjet主体认证
     *    2.1 需要在当前realm中调用service来验证,当前用户是否在数据库中存在
     *    2.2 盐加密
     */
    public class MyRealm extends AuthorizingRealm {
        private ShiroUserService shiroUserService;
    
        public ShiroUserService getShiroUserService() {
            return shiroUserService;
        }
    
        public void setShiroUserService(ShiroUserService shiroUserService) {
            this.shiroUserService = shiroUserService;
        }
    
        /**
         * 授权
         * @param principals
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            ShiroUser shiroUser = this.shiroUserService.queryByName(principals.getPrimaryPrincipal().toString());
            Set<String> roleids = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
            Set<String> perIds = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
    
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            info.setRoles(roleids);
            info.setStringPermissions(perIds);
            return info;
        }
    
        /**
         * 认证
         * @param token   从jsp页面传递过来的用户名和密码组成成的一个token对象
         * @return
         * @throws AuthenticationException
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            String userName =  token.getPrincipal().toString();
            String pwd =  token.getPrincipal().toString();
            ShiroUser shiroUser = this.shiroUserService.queryByName(userName);
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    shiroUser.getUsername(),
                    shiroUser.getPassword(),
                    ByteSource.Util.bytes(shiroUser.getSalt()),
                    this.getName()
            );
            return info;
        }
    }

    注解式开发

    @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

    springmvc-servlet.xml中配置 

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

    Controller层

     /**
         * 身份认证的注解
         * @param request
         * @param response
         * @return
         */
        @RequiresUser
        @RequestMapping("/passUser")
        public  String passUser(HttpServletRequest request, HttpServletResponse response) {
            return "admin/addUser";
        }
    
        /**
         * 角色认证的注解
         * @param request
         * @param response
         * @return
         *
         * 当方法必须同时具备1、4的角色id,才能被访问
         */
        @RequiresRoles(value = {"1","4"},logical = Logical.OR)
        @RequestMapping("/passRole")
        public  String passRole(HttpServletRequest request, HttpServletResponse response) {
            return "admin/listUser";
        }
    
        /**
         * 权限认证的注解
         * @param request
         * @param response
         * @return
         */
        @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
        @RequestMapping("/passPer")
        public  String passPer(HttpServletRequest request, HttpServletResponse response) {
            return "admin/resetPwd";
        }
    
        /**
         * 身份、角色、权限认证失败后的处理方式
         * @param request
         * @param response
         * @return
         */
        @RequestMapping("/unauthorized")
        public  String xxx(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("错误!!");
            return  "unauthorized";
        }

    main.jsp

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

    结果:直接进入会跳到错误处理页面,只有相关权限的才能进入

     

  • 相关阅读:
    二叉搜索树与双向链表
    TCP 三次握手与四次挥手
    复杂链表的复制
    二叉树中和为某一值的路径
    二叉搜索树的后序遍历序列
    从上往下打印二叉树
    栈的压入、弹出序列
    jenkins 持续集成和交付——一个构件小栗子前置(三)
    jenkins 持续集成和交付——gogs安装(外篇)
    jenkins 持续集成和交付——安装与账户安全还有凭证(二)
  • 原文地址:https://www.cnblogs.com/chenjiahao9527/p/11678227.html
Copyright © 2020-2023  润新知