shiro授权

目录

一、shiro授权角色、权限

1、Mapper层、servlet层

二、shiro的 授权的方法 

运行:

 二、Shiro的注解式开发

1、常用注解介绍

2、测试

controller层


一、shiro授权角色、权限

1、Mapper层、servlet层

UserMapper.xml中新增方法

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

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

UserMapper.java

package com.zking.ssm.mapper;

import com.zking.ssm.model.User;
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 queryByName(@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.java

package com.zking.ssm.biz;

import com.zking.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 queryByName(String userName);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

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

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

UserBizImpl.java

package com.zking.ssm.impl;

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

import java.util.Set;

/**
 * @author 白未
 * @site 3185579318
 * @company xxx公司
 * @create  2022-08-26 12:54
 */
@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 queryByName(String userName) {
        return userMapper.queryByName(userName);
    }

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

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

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

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

二、shiro的 授权的方法 

package com.zking.ssm.shiro;

import com.zking.ssm.biz.UserBiz;
import com.zking.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.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Set;

/**
 * @author 白未
 * @site 3185579318
 * @company xxx公司
 * @create  2022-08-26 13:00
 */

public class MyRealm extends AuthorizingRealm {
    public UserBiz userBiz;

    public UserBiz getUserBiz() {
        return userBiz;
    }

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


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = principalCollection.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 authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = authenticationToken.getPrincipal().toString();
        User user = userBiz.queryByName(userName);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()//realm的名字
        );
        return info;
    }
}

角色与权限的结果要与applicationContext-shiro.xml的配置保持一致 

角色:4
权限:2

运行:

登录zs

 点击用户新增,没有权限

 zdm登录点击用户新增

 zs登录点击老师简介

ls登录点击老师简介

 

 二、Shiro的注解式开发

1、常用注解介绍

 @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

2、测试

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

Shirocontroller.java

package com.zking.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 白未
 * @site 3185579318
 * @company xxx公司
 * @create  2022-08-29 10:11
 */
@RequestMapping("/shiro")
@Controller
public class ShiroController {
    //RequiresUser代表当前方法只有登录后才能访问
    //RequiresUser等价于Spring-shiro.xml中的/user/updatePwd.jsp=authc配置
    @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.AND)
    @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("/passPermissions")
    public String passPermissions(){
        System.out.println("权限认认证通过");
        return "admin/addUser";
    }
}

 OR代表只要满足value中的一个条件即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值