shiro 授权和注解开发

shiro 授权和注解开发

数据库的表设计
在这里插入图片描述

shiro授权

在ShiroUserMapper.xml中新增内容

<!--  这是根据用户id获取到所拥有的角色集合-->
  <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>
  
  <!--  这是根据用户id获取到所拥有的权限集合-->
  <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>

Service层:

  • ShiroUserService.java
package com.lin.service;

import com.lin.model.ShiroUser;
import org.springframework.stereotype.Repository;

import java.util.Set;

/**
 * @authorlinfan
 * @site www.linfanmage.com
 * @company xxx公司
 * @create  2019-10-13 19:14
 */
@Repository
public interface ShiroUserService  {
    /**
     * 用于注册
     * @param shiroUser
     * @return
     */
     int insert(ShiroUser shiroUser);
    /**
     * 用于认证
     * @param uname
     * @return
     */
    public ShiroUser queryByName(String uname);

    /**
     * 用于授权
     * @param uid
     * @return
     */
    Set<String> getRolesByUserId(Integer uid);

    Set<String> getPersByUserId(Integer uid);
}

  • ShiroUserServiceImpl.java
package com.lin.service.impl;

import com.lin.mapper.ShiroUserMapper;
import com.lin.model.ShiroUser;
import com.lin.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @authorlinfan
 * @site www.linfanmage.com
 * @company xxx公司
 * @create  2019-10-13 19:19
 */
@Service("shiroUserService")
public abstract class ShiroUserServiceImpl implements ShiroUserService {

    @Autowired
    private ShiroUserMapper shiroUserMapper;
    @Override
    public ShiroUser queryByName(String uname) {
        return shiroUserMapper.queryByName(uname);
    }

    @Override
    public Set<String> getRolesByUserId(Integer uid) {
        return shiroUserMapper.getRolesByUserId(uid);
    }

    @Override
    public Set<String> getPersByUserId(Integer uid) {
        return shiroUserMapper.getPersByUserId(uid);
    }
}

重写自定义realm中的授权方法:

@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("用户授权...");
        String username = principals.getPrimaryPrincipal().toString();
        ShiroUser user = shiroUserService.queryByName(username);
        Set<String> roles = shiroUserService.getRolesByUserId(user.getUserid());
        Set<String> pers = shiroUserService.getPersByUserId(user.getUserid());

//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addRoles(roles);
//        info.addStringPermissions(pers);

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(pers);

        return info;
    }

shiro注解式开发

常用注解介绍:

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

Controller层:

  • shiroUserController中添加方法


    /**
     * 用户必须登录后才能请求
     * @param request
     * @return
     */
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest request){
        return "admin/addUser";
    }


    /**
     * 用户必须拥有角色id为 1 和 4 的这两个角色
     *
     * Logical.RO 就是或的意思,也就是说用户 必须拥有角色id为 1 或 4 的这两个角色
     * @param request
     * @return
     */
    @RequiresRoles(value = {"1","4"},logical = Logical.AND)
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest request){
        return "admin/listUser";
    }


    /**
     * 用户必须拥有 user:update 或 user:view 权限才能访问
     *
     * 当然:Logical.OR 能改成 Logical.AND
     * @param request
     * @return
     */
    @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
    @RequestMapping("/passPer")
    public String passPer(HttpServletRequest request){
        return "admin/resetPwd";
    }

  • Springmvc.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>

  • 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>
</ul>

  • 测试结果
zs只能查看身份认证的按钮内容
ls、ww可以看权限认证按钮内容
zdm可以看所有按钮的内容
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值