shiro授权

注:此篇博客是在上篇shiro认证基础上写的

一、shiro授权角色、权限

在这里插入图片描述
ShiroUserMapper

package com.ningjie.ssm.mapper;

import com.ningjie.ssm.model.ShiroUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.Set;

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

    int insert(ShiroUser record);

    int insertSelective(ShiroUser record);

    ShiroUser selectByPrimaryKey(Integer userid);

    int updateByPrimaryKeySelective(ShiroUser record);

    int updateByPrimaryKey(ShiroUser record);

    ShiroUser selectByName(@Param("uname") String uname);

    /**
     * 查询角色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>

ShiroUserService

package com.ningjie.ssm.service;

import com.ningjie.ssm.model.ShiroUser;

import java.util.Set;

/**
 * @author NingJie
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2019-11-03 20:16
 */
public interface ShiroUserService {
    Set<String> getRolesByUserId(Integer userid);
    Set<String> getPersByUserId(Integer userid);
}

ShiroUserServiceImpl

package com.ningjie.ssm.service.impl;

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

import java.util.Set;

/**
 * @author NingJie
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2019-11-03 20:18
 */
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;
    @Override
    public Set<String> getRolesByUserId(Integer userid) {
        return shiroUserMapper.getRolesByUserId(userid);
    }

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

MyRealm

package com.ningjie.ssm.shiro;

import com.ningjie.ssm.model.ShiroUser;
import com.ningjie.ssm.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 NingJie
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2019-11-03 20:06
 *
 * 替换掉了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) {
        //获取唯一的身份
        String uname=principalCollection.getPrimaryPrincipal().toString();
        ShiroUser shiroUser = this.shiroUserService.selectByName(uname);
        Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(rolesByUserId);
        info.setStringPermissions(persByUserId);
        return info;
    }
}

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

注解的使用
主页中加入jsp代码

 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>

Spring-mvc.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>

ShiroUserController

package com.ningjie.ssm.controller;

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

/**
 * @author NingJie
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2019-11-03 23:16
 */
@Controller
public class ShiroUserContrller {
    @Autowired
    private ShiroUserService shiroUserService;
  

    @RequiresUser
    @ResponseBody
    @RequestMapping("/passUser")
    public String passUser(){
        return "身份OK!";
    }

    @RequiresRoles(value={"1","4"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("/passRole")
    public String passRole(){
        return "角色OK!";
    }

    @RequiresPermissions(value = {"user:update","user:create"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("/passPer")
    public String passPer(){
        return "权限OK!";
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值