Shiro 授权&注解式开发 - SSM

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_44641053/article/details/102573459

Shiro 授权&注解式开发 - SSM

权限图解如下:
在这里插入图片描述

Shiro 授权

  1. 添加角色和权限的授权方法

     		  //根据username查询该用户的所有角色,用于角色验证
     		  Set<String> findRoles(String username);
     		
     		  //根据username查询他所拥有的权限信息,用于权限判断
     		  Set<String> findPermissions(String username);
    
  2. 自定义 Realm 配置 Shiro 授权认证

     		  1) 获取验证身份(用户名)
     		  
     		  2) 根据身份(用户名)获取角色和权限信息
     		  
     		  3) 将角色和权限信息设置到SimpleAuthorizationInfo
     		  SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
     		  info.setRoles(roles);
     		  info.setStringPermissions(permissions);
    
  3. 使用 Shiro 标签实现权限验证

    3.1 导入 Shiro 标签库

     		<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
    

    3.2 Shiro 标签库

     		  guest标签 :验证当前用户是否为“访客”,即未认证(包含未记住)的用户
     		  
     		  user标签 :认证通过或已记住的用户
     		  
     		  authenticated标签 :已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在
     		  
     		  notAuthenticated标签 :未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户
     		  
     		  principal 标签 :输出当前用户信息,通常为登录帐号信息 
     		  
     		  hasRole标签 :验证当前用户是否属于该角色 
     		  
     		  lacksRole标签 :与hasRole标签逻辑相反,当用户不属于该角色时验证通过
     		  
     		  hasAnyRole标签 :验证当前用户是否属于以下任意一个角色
     		  
     		  hasPermission标签 :验证当前用户是否拥有指定权限
     		  
     		  lacksPermission标签 :与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过 
    

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

ShiroUserService.java

扫描二维码关注公众号,回复: 7565376 查看本文章
package com.dj.ssm.service;

import com.dj.ssm.model.ShiroUser;

import java.util.Set;

public interface ShiroUserService {
    public Set<String> getRolesByUserId(Integer userId);

    public Set<String> getPersByUserId(Integer userId);

    public ShiroUser queryByName(String userName);
}


ShiroUserServiceImpl.java

package com.dj.ssm.service.impl;

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

import java.util.Set;

@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);
    }

    @Override
    public ShiroUser queryByName(String userName) {
        return shiroUserMapper.queryByName(userName);
    }
}


重写自定义 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. 配置注解权限验证

    4.1 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
    

    4.2 开启注解

    注意:必须将Shiro注解的开启放置到spring-mvc.xml中(即放在springMVC容器中加载),不然Shiro注解开启无效!!!

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

    4.3 注解权限验证失败不跳转路径问题

    问题原因:由于我们架构是用springmvc框架来搭建的所以项目的路径跳转是由springmvc 来控制的,也就是说我们在shiro里面的配置没有用

     		  <!-- 身份验证成功,跳转到指定页面 -->
     		  <property name="successUrl" value="/index.jsp"/>                //没有用,达不到预期效果
     		  
     		  <!-- 权限验证失败,跳转到指定页面 -->
     		  <property name="unauthorizedUrl" value="/user/noauthorizeUrl"/> //没有用,达不到预期效果
    

    解决方案: springmvc中有一个org.springframework.web.servlet.handler.SimpleMappingExceptionResolver 类就可以解决这个问题

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

@RequiresUser
@RequestMapping("/passUser")
public String passUser(HttpServletRequest request){
    return "admin/addUser";
}

@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@RequestMapping("/passRole")
public String passRole(HttpServletRequest request){
    return "admin/listUser";
}

@RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
@RequestMapping("/passPer")
public String passPer(HttpServletRequest request){
    return "admin/resetPwd";
}

@RequestMapping("/unauthorized")
public String unauthorized(){
    return "unauthorized";
}


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可以看所有按钮的内容

猜你喜欢

转载自blog.csdn.net/qq_44641053/article/details/102573459