shiro授权SSM

目录

一、shiro授权角色、权限

UserMapper.java

UserMapper.xml

userbiz 

applicationContext-shiro.xml

二、Shiro的注解式开发

springmvc-servlet.xml

 ShiroController


 

一、shiro授权角色、权限

 

1、UserMapper.java

package com.zlp.ssm.mapper;

import com.zlp.ssm.model.User;
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(String userName);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    Set<String> getRolesByUserId(String userName);

    Set<String> getPersByUserId(String userName);
}

2、UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zlp.ssm.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.zlp.ssm.model.User" >
    <constructor >
      <idArg column="userid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="salt" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="createdate" jdbcType="TIMESTAMP" javaType="java.util.Date" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    userid, username, password, salt, createdate
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_shiro_user
    where userid = #{userid,jdbcType=INTEGER}
  </select>
  <select id="queryByName" resultType="com.zlp.ssm.model.User" parameterType="java.lang.String">
    select
    <include refid="Base_Column_List" />
    from t_shiro_user
    where userName = #{userName}
  </select>

  <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.String">
  select ur.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.username = #{username}
  </select>
  <select id="getPersByUserId" 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,t_shiro_permission p
  where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
  and u.username = #{username}
  </select>


  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_shiro_user
    where userid = #{userid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.zlp.ssm.model.User" >
    insert into t_shiro_user (userid, username, password, 
      salt, createdate)
    values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{salt,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.zlp.ssm.model.User" >
    insert into t_shiro_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userid != null" >
        userid,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="salt != null" >
        salt,
      </if>
      <if test="createdate != null" >
        createdate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userid != null" >
        #{userid,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null" >
        #{salt,jdbcType=VARCHAR},
      </if>
      <if test="createdate != null" >
        #{createdate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zlp.ssm.model.User" >
    update t_shiro_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null" >
        salt = #{salt,jdbcType=VARCHAR},
      </if>
      <if test="createdate != null" >
        createdate = #{createdate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where userid = #{userid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zlp.ssm.model.User" >
    update t_shiro_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      salt = #{salt,jdbcType=VARCHAR},
      createdate = #{createdate,jdbcType=TIMESTAMP}
    where userid = #{userid,jdbcType=INTEGER}
  </update>
</mapper>

userbiz 

package com.zlp.ssm.biz;

import com.zlp.ssm.model.User;

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> getRolesByUserId(String userName);

    Set<String> getPersByUserId(String userName);

}

UserBizImpl  

package com.zlp.ssm.biz.impl;

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

import java.util.Set;

/**
 * @author zlp
 * @create 2022-08-25 19:10
 */
@Service("UserService")
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> getRolesByUserId(String userName) {
        return userMapper.getRolesByUserId(userName);
    }

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

5、applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置自定义的Realm-->
    <bean id="shiroRealm" class="com.zlp.ssm.shiro.Myrealm">
        <property name="userBiz" ref="UserService" />
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--以下三个配置告诉shiro将如何对用户传来的明文密码进行加密-->
        <property name="credentialsMatcher">
            <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--指定hash算法为MD5-->
                <property name="hashAlgorithmName" value="md5"/>
                <!--指定散列次数为1024次-->
                <property name="hashIterations" value="1024"/>
                <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储-->
                <property name="storedCredentialsHexEncoded" value="true"/>
            </bean>
        </property>
    </bean>

    <!--注册安全管理器-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="shiroRealm" />
    </bean>

    <!--Shiro核心过滤器-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 身份验证失败,跳转到登录页面 -->
        <property name="loginUrl" value="/login"/>
        <!-- 身份验证成功,跳转到指定页面 -->
        <!--<property name="successUrl" value="/index.jsp"/>-->
        <!-- 权限验证失败,跳转到指定页面 -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                <!--
                注:anon,authcBasic,auchc,user是认证过滤器
                    perms,roles,ssl,rest,port是授权过滤器
                -->
                <!--anon 表示匿名访问,不需要认证以及授权-->
                <!--authc表示需要认证 没有进行身份认证是不能进行访问的-->
                <!--roles[admin]表示角色认证,必须是拥有admin角色的用户才行-->
                /user/login=anon
                /user/updatePwd.jsp=authc
                /admin/*.jsp=roles[4]
                /user/teacher.jsp=perms[2]
                <!-- /css/**               = anon
                 /images/**            = anon
                 /js/**                = anon
                 /                     = anon
                 /user/logout          = logout
                 /user/**              = anon
                 /userInfo/**          = authc
                 /dict/**              = authc
                 /console/**           = roles[admin]
                 /**                   = anon-->
            </value>
        </property>
    </bean>

    <!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>


package com.zlp.ssm.shiro;

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

import java.util.Set;

/**
 * @author zlp
 * @create 2022-08-25 19:24
 */
public class Myrealm extends AuthorizingRealm {
    private UserBiz userBiz;

    public UserBiz getUserBiz() {
        return userBiz;
    }

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

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("用户授权...");
        String username = principals.getPrimaryPrincipal().toString();
        User user = userBiz.queryByName(username);
        Set<String> roles = userBiz.getRolesByUserId(user.getUsername());
        Set<String> pers = userBiz.getPersByUserId(user.getUsername());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(pers);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份验证...");
        String username = token.getPrincipal().toString();
        String password = token.getCredentials().toString();
        User user = userBiz.queryByName(username);
        AuthenticationInfo info=new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()
        );
        return info;
    }
}

运行结果 

 

二、Shiro的注解式开发

1、springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.zlp.ssm"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--3) ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
    <mvc:resources location="/static/" mapping="/js/**"/>

    <!--文件上传:多功能解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

    <!--配置拦截器-->
    <!--<mvc:interceptors>
        &lt;!&ndash;针对于所有的请求进行拦截&ndash;&gt;
        <bean class="com.zlp.ssm.intercept.OneHandlerInterceptor"></bean>
    </mvc:interceptors>-->
    <!--配置拦截器链-->
   <!-- <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.zlp.ssm.intercept.OneHandlerInterceptor"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/clz/**"/>
            <bean class="com.zlp.ssm.intercept.TwoHandlerInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>-->

    <!--支持json数据返回的适配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>
    <bean id="mappingJackson2HttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
       <!-- 处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>text/json;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!--统一异常处理-->
    <!-- springmvc提供的简单异常处理器 -->
    <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        &lt;!&ndash; 定义默认的异常处理页面 &ndash;&gt;
        <property name="defaultErrorView" value="error"/>
        &lt;!&ndash; 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception &ndash;&gt;
        <property name="exceptionAttribute" value="ex"/>
        &lt;!&ndash; 定义需要特殊处理的异常,这是重要点 &ndash;&gt;
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.RuntimeException">error</prop>
            </props>
            &lt;!&ndash; 还可以定义其他的自定义异常 &ndash;&gt;
        </property>
    </bean>-->

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


</beans>


 ShiroController

package com.zlp.ssm.web;

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;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zlp
 * @create 2022-08-26 19:33
 */
@RequestMapping("/shiro")
@Controller
public class ShiroController {

    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest request){
        System.out.println("身份认证通过..");
        return "admin/addUser";
    }

    @RequiresRoles(value = {"1","4"},logical = Logical.AND)
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest request){
        System.out.println("角色认证通过..");
        return "admin/addUser";
    }

    @RequiresPermissions(value = {"2"},logical = Logical.AND)
    @RequestMapping("/passPermission")
    public String permission(HttpServletRequest request){
        System.out.println("权限认证通过..");
        return "admin/addUser";
    }
}

 

 没有登录时:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值