码迷,mamicode.com
首页 > 其他好文 > 详细

Shiro03

时间:2019-10-15 13:17:18      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:cti   div   set   insert   guest   etc   alc   eid   override   

1、shiro授权角色、权限

2、Shiro的注解式开发

shiro权限思路

技术图片

授权

ShiroUserMapper中定义两个方法

//    通过用户ID查询角色
    Set<String> getRolesByUserId(Integer userId);
//    通过用户ID查询权限
    Set<String> getPersByUserId(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>

Service层

package com.liuwenwu.service.impl;

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

import java.util.Set;

/**
 * @author LWW
 * @site www.lww.com
 * @company
 * @create 2019-10-13 16:14
 */
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;

    @Override
    public ShiroUser queryByName(String uname) {

        return shiroUserMapper.queryByName(uname);
    }

    /**
     * 新增用户
     * @param record
     * @return
     */
    @Override
    public int insert(ShiroUser record) {

        return shiroUserMapper.insert(record);
    }

    /**
     * 通过用户ID查询角色
     * @param userId
     * @return
     */
    @Override
    public Set<String> getRolesByUserId(Integer userId) {
        return shiroUserMapper.getRolesByUserId(userId);
    }

    /**
     * 通过用户ID查询权限
     * @param userId
     * @return
     */
    @Override
    public Set<String> getPersByUserId(Integer userId) {
        return shiroUserMapper.getPersByUserId(userId);
    }
}

ShiroUserServiceImpl

package com.liuwenwu.service.impl;

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

import java.util.Set;

/**
 * @author LWW
 * @site www.lww.com
 * @company
 * @create 2019-10-13 16:14
 */
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;

    @Override
    public ShiroUser queryByName(String uname) {

        return shiroUserMapper.queryByName(uname);
    }

    /**
     * 新增用户
     * @param record
     * @return
     */
    @Override
    public int insert(ShiroUser record) {

        return shiroUserMapper.insert(record);
    }

    /**
     * 通过用户ID查询角色
     * @param userId
     * @return
     */
    @Override
    public Set<String> getRolesByUserId(Integer userId) {
        return shiroUserMapper.getRolesByUserId(userId);
    }

    /**
     * 通过用户ID查询权限
     * @param userId
     * @return
     */
    @Override
    public Set<String> getPersByUserId(Integer userId) {
        return shiroUserMapper.getPersByUserId(userId);
    }
}

重写自定义MyRealm中的授权方法

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        当前登录的用户
        ShiroUser shiroUser = this.shiroUserService.queryByName(principals.getPrimaryPrincipal().toString());
        Set<String> rolrids = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        Set<String> perdis = this.shiroUserService.getPersByUserId(shiroUser.getUserid());

        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        info.setRoles(rolrids);
        info.setStringPermissions(perdis);
        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

 

ShiroUserController

    /**
     * 身份认证的注解
     * @param req
     * @param resp
     * @return
     */
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest req, HttpServletResponse resp){
        return "admin/addUser";
    }

    /**
     * 角色认证的注解
     * @param req
     * @param resp
     * @return
     * 当前方法必须同时具备1、4的角色ID才能被访问
     */
    @RequiresRoles(value = {"1","4"},logical = Logical.OR)
    @RequestMapping("/passRole")
    public String passPole(HttpServletRequest req, HttpServletResponse resp){
        return "admin/listUser";
    }

    /**
     * 权限认证的注解
     * @param req
     * @param resp
     * @return
     */
    @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
    @RequestMapping("/passPer")
    public String passPer(HttpServletRequest req, HttpServletResponse resp){
        return "admin/resetPwd";
    }

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>

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>
</ul>
效果: 没通过验证会跳到 unauthorized.jsp页面

技术图片

通过验证:

技术图片



Shiro03

标签:cti   div   set   insert   guest   etc   alc   eid   override   

原文地址:https://www.cnblogs.com/liuwenwu9527/p/11676878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!