ssm项目整合shiro

之前有一篇文章是简单的介绍shiro的,但是现在需要整合到ssm的项目中,下面是步骤:
1、数据库中创建五张表,分别是用户表t_user、角色表t_role、权限表t_permission、用户和角色的关系表t_user_role、角色和权限表t_role_permission.

DROP TABLE IF EXISTS `t_permission`;
CREATE TABLE `t_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createtime` date DEFAULT NULL,
  `updatetime` date DEFAULT NULL,
  `isdelete` tinyint(4) NOT NULL DEFAULT '0',
  `permissionname` varchar(10) DEFAULT NULL COMMENT '权限名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_permission
-- ----------------------------
INSERT INTO `t_permission` VALUES ('1', '2018-02-03', '2018-02-03', '0', 'add');
INSERT INTO `t_permission` VALUES ('2', '2018-02-03', '2018-02-03', '0', 'query');
INSERT INTO `t_permission` VALUES ('3', '2018-02-03', '2018-02-03', '0', 'update');
INSERT INTO `t_permission` VALUES ('4', '2018-02-03', '2018-02-03', '0', 'delete');

DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createtime` date DEFAULT NULL,
  `updatetime` date DEFAULT NULL,
  `isdelete` tinyint(4) NOT NULL DEFAULT '0',
  `rolename` varchar(10) DEFAULT NULL COMMENT '角色名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_role
-- ----------------------------
INSERT INTO `t_role` VALUES ('1', '2018-02-03', '2018-02-03', '0', 'admin');
INSERT INTO `t_role` VALUES ('2', '2018-02-03', '2018-02-03', '0', 'normal');
INSERT INTO `t_role` VALUES ('3', '2018-02-03', '2018-02-03', '0', 'teacher');
INSERT INTO `t_role` VALUES ('4', '2018-02-03', '2018-02-03', '0', 'student');

-- ----------------------------
-- Table structure for `t_role_permission`
-- ----------------------------
DROP TABLE IF EXISTS `t_role_permission`;
CREATE TABLE `t_role_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createtime` date DEFAULT NULL,
  `updatetime` date DEFAULT NULL,
  `isdelete` tinyint(4) NOT NULL DEFAULT '0',
  `roleid` int(11) DEFAULT NULL COMMENT '角色名',
  `permissionid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_role_permission
-- ----------------------------
INSERT INTO `t_role_permission` VALUES ('1', null, null, '0', '1', '1');
INSERT INTO `t_role_permission` VALUES ('2', null, null, '0', '1', '2');
INSERT INTO `t_role_permission` VALUES ('3', null, null, '0', '1', '3');
INSERT INTO `t_role_permission` VALUES ('4', null, null, '0', '1', '4');
INSERT INTO `t_role_permission` VALUES ('5', null, null, '0', '2', '2');
INSERT INTO `t_role_permission` VALUES ('6', null, null, '0', '3', '1');
INSERT INTO `t_role_permission` VALUES ('7', null, null, '0', '3', '2');
INSERT INTO `t_role_permission` VALUES ('8', null, null, '0', '3', '3');
INSERT INTO `t_role_permission` VALUES ('9', null, null, '0', '4', '2');

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `createtime` date DEFAULT NULL,
  `updatetime` date DEFAULT NULL,
  `passwordmd` varchar(32) DEFAULT NULL COMMENT '加密后的密码',
  `password` varchar(32) DEFAULT NULL COMMENT '加密前的密码',
  `salt` varchar(32) NOT NULL COMMENT '盐值',
  `grand` tinyint(2) NOT NULL DEFAULT '0' COMMENT '权限  0表示的是没有激活, 1 表示用户激活了',
  `activecode` varchar(100) NOT NULL COMMENT '激活码',
  `isdelete` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否删除   0没有删除      1 删除了',
  `email` varchar(32) DEFAULT NULL COMMENT '邮箱',
  `phone` varchar(32) DEFAULT NULL COMMENT '电话',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'admin', '2018-02-03', '2018-02-03', '2fd765dc46f3e494869bc79ad6193e3e', '8888', '7336b40882fb4a1a9c432e624c279717', '0', '123', '0', null, null);
INSERT INTO `t_user` VALUES ('2', 'chen', '2018-02-03', '2018-02-03', '92d75801c14395e38445ad69e618f5d1', '456', '0b61ff3eea8946189781f470fda59b31', '0', '111', '0', null, null);
INSERT INTO `t_user` VALUES ('3', 'wang', '2018-02-03', '2018-02-03', '5be92443feac4d454cc53b12d93c195b', '555', '2377aa75721e460aa4777f91e3a43df8', '0', '111', '0', null, null);

-- ----------------------------
-- Table structure for `t_user_role`
-- ----------------------------
DROP TABLE IF EXISTS `t_user_role`;
CREATE TABLE `t_user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createtime` date DEFAULT NULL,
  `updatetime` date DEFAULT NULL,
  `isdelete` tinyint(4) NOT NULL DEFAULT '0',
  `roleid` int(11) DEFAULT NULL COMMENT '角色id',
  `userid` int(11) DEFAULT NULL COMMENT '用户id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user_role
-- ----------------------------
INSERT INTO `t_user_role` VALUES ('1', null, null, '0', '1', '1');
INSERT INTO `t_user_role` VALUES ('2', null, null, '0', '2', '1');
INSERT INTO `t_user_role` VALUES ('3', null, null, '0', '3', '1');
INSERT INTO `t_user_role` VALUES ('4', null, null, '0', '4', '1');
INSERT INTO `t_user_role` VALUES ('5', null, null, '0', '2', '2');
INSERT INTO `t_user_role` VALUES ('6', null, null, '0', '4', '2');
INSERT INTO `t_user_role` VALUES ('7', null, null, '0', '3', '3');

上面的sql语句中,用户表里面有一个加盐字段,这个加盐字段是对用户输入的密码再一次加密防止给破解,还有就是用户修改密码的时候加盐字段需要重新设置。这里还有一个用户输入的密码字段,这个字段是方便我去做比较,才保留这个字段的,按照正常情况的话这个字段是不保存在数据库的,因为数据库给黑客破解而且密码是明文,就会造成软件得漏洞。

2导入相关包
pom.xml文件:

<!-- Spring 整合Shiro需要的依赖 -->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.2.1</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>1.2.1</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-ehcache</artifactId>
                <version>1.2.1</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.2.1</version>
            </dependency>

3pojo对象
ShiroUser,ShiroRole,ShiroPermission

package com.ljlx.pojo;

import java.util.Set;

public class ShiroUser {
    private String username;
    private String passwordmd;
    private String salt;

    private Set<ShiroRole> role;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswordmd() {
        return passwordmd;
    }

    public void setPasswordmd(String passwordmd) {
        this.passwordmd = passwordmd;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Set<ShiroRole> getRole() {
        return role;
    }

    public void setRole(Set<ShiroRole> role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "ShiroUser [username=" + username + ", passwordmd=" + passwordmd
                + ", salt=" + salt + ", role=" + role + "]";
    }



}

package com.ljlx.pojo;

import java.util.Set;

public class ShiroRole {
    private Set<ShiroPermission> permissions;
    private String rolename;
    public String getRolename() {
        return rolename;
    }

    public void setRolename(String rolename) {
        this.rolename = rolename;
    }

    public Set<ShiroPermission> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<ShiroPermission> permissions) {
        this.permissions = permissions;
    }

    @Override
    public String toString() {
        return "ShiroRole [permissions=" + permissions + ", rolename="
                + rolename + "]";
    }

}


package com.ljlx.pojo;

public class ShiroPermission {
    private String permissionname;

    public String getPermissionname() {
        return permissionname;
    }

    public void setPermissionname(String permissionname) {
        this.permissionname = permissionname;
    }

    @Override
    public String toString() {
        return "ShiroPermission [permissionname=" + permissionname + "]";
    }

}

4TRoleMapper.java 和TRoleMapper.xml

package com.ljlx.mapper;

import com.ljlx.pojo.ShiroUser;

public interface TRoleMapper {
    ShiroUser queryRoleByUsername(String username);
}

TRoleMapper.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.ljlx.mapper.TRoleMapper" >
  <resultMap id="BaseResultMap" type="com.ljlx.pojo.ShiroUser" >
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="passwordmd" property="passwordmd" jdbcType="VARCHAR" />
    <result column="salt" property="salt" jdbcType="VARCHAR" />
    <collection property="role" ofType="com.ljlx.pojo.ShiroRole">
        <result column="rolename" property="rolename" jdbcType="VARCHAR" />
        <collection property="permissions" ofType="com.ljlx.pojo.ShiroPermission">
            <result column="permissionname" property="permissionname" jdbcType="VARCHAR" />
        </collection>
    </collection>
  </resultMap>
  <select id="queryRoleByUsername" resultMap="BaseResultMap" parameterType="java.lang.String">
    select t_user.username,t_user.passwordmd,t_user.salt,t_role.rolename,t_permission.permissionname
    from t_permission,t_role,t_role_permission,t_user,t_user_role 
    where t_user.id = t_user_role.userid and 
t_user_role.roleid = t_role.id and 
t_role.id = t_role_permission.roleid and 
t_role_permission.permissionid = t_permission.id AND
t_user.isdelete = 0 and t_user_role.isdelete = 0 and t_permission.isdelete = 0 and t_role.isdelete = 0 and t_role_permission.isdelete = 0 and 
t_user.username = #{username,jdbcType=VARCHAR} 
  </select>

</mapper>

5自定义reamle

package com.ljlx.web.shiro;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

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.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
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.springframework.beans.factory.annotation.Autowired;

import com.ljlx.mapper.TRoleMapper;
import com.ljlx.pojo.ShiroPermission;
import com.ljlx.pojo.ShiroRole;
import com.ljlx.pojo.ShiroUser;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired 
    private TRoleMapper tRoleMapper;
    /* 
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String loginname = (String) principals.fromRealm(getName()).iterator().next();
        ShiroUser username = tRoleMapper.queryRoleByUsername(loginname);
        if(username != null){
        Set<ShiroRole> role = username.getRole();
        //角色名的集合  
        Set<String> roles = new HashSet<String>();  
        //权限名的集合  
        Set<String> permissions = new HashSet<String>();  
        Iterator<ShiroRole> it = role.iterator();  
        while(it.hasNext()){  
            roles.add(it.next().getRolename());  
            for(ShiroPermission per:it.next().getPermissions()){  
                permissions.add(per.getPermissionname());  
            }  
        }  
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
        authorizationInfo.addRoles(roles);  
        authorizationInfo.addStringPermissions(permissions); 
        return authorizationInfo;  
        }
        throw new UnknownAccountException();
    }
    /* 
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        ShiroUser user = tRoleMapper.queryRoleByUsername(token.getUsername());
        if(user != null){
            String string2 = new StringBuffer().append(token.getPassword()).toString();
            if(string2.equals(user.getPasswordmd())){
                return new SimpleAuthenticationInfo(user.getUsername(), user.getPasswordmd(), getName());
            }
        }
        throw new UnknownAccountException();
    }

}

6applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <description>Shiro Configuration</description>  

    <!-- Shiro's main business-tier object for web-enabled applications -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realm" ref="myShiroRealm" />  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- 項目自定义的Realm -->  
    <bean id="myShiroRealm" class="com.ljlx.web.shiro.MyShiroRealm">  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- Shiro Filter -->  
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <property name="securityManager" ref="securityManager" />  
        <property name="loginUrl" value="/login.jhtml" />  
        <property name="successUrl" value="/loginsuccess.jhtml" />  
        <property name="unauthorizedUrl" value="/error.jhtml" />  
        <property name="filterChainDefinitions">  
            <value>  
                /index.jhtml = authc  
                /login.jhtml = anon
                /checkLogin.json = anon  
                /loginsuccess.jhtml = authc  
                /logout.json = anon  
                /** = authc  
            </value>  
        </property>  
    </bean>  

    <!-- 用户授权信息Cache -->  
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  

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

    <!-- AOP式方法级权限检查 -->  
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
        depends-on="lifecycleBeanPostProcessor">  
        <property name="proxyTargetClass" value="true" />  
    </bean>  

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager" />  
    </bean>  

</beans> 

7web.xml

<!-- shiro过滤器 -->
<filter>  
    <filter-name>shiroFilter</filter-name>  
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    <init-param>  
        <param-name>targetFilterLifecycle</param-name>  
        <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>shiroFilter</filter-name>  
    <url-pattern>*.jhtml</url-pattern>  
    <url-pattern>*.json</url-pattern>  
</filter-mapping>

8加密工具类com.ljlx.web.utils.DecriptUtil

package com.ljlx.web.utils;

import java.math.BigInteger;
import java.security.MessageDigest;

public class DecriptUtil {
    public static String MD5(String str){
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
           return "";
        }
    }
}

9controller

package com.ljlx.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONUtils;
import com.ljlx.exception.BusinessException;
import com.ljlx.mapper.TRoleMapper;
import com.ljlx.pojo.ShiroUser;
import com.ljlx.web.utils.DecriptUtil;

@Controller
public class UserRoleController {

    @Autowired
    private TRoleMapper tRoleMapper;
    @RequestMapping("/index.jhtml")
    public ModelAndView getIndex(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView("index");
        return mav;
    }

    @RequestMapping("/exceptionForPageJumps.jhtml")
    public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception {
        throw new BusinessException("");
    }

    @RequestMapping(value="/businessException.json", method=RequestMethod.POST)
    @ResponseBody  
    public String businessException(HttpServletRequest request) throws Exception{
        throw new BusinessException("");
    }

    @RequestMapping(value="/otherException.json", method=RequestMethod.POST)
    @ResponseBody  
    public String otherException(HttpServletRequest request) throws Exception {
        throw new Exception();
    }

    //跳转到登录页面
    @RequestMapping("/login.jhtml")
    public ModelAndView login() throws Exception {
        ModelAndView mav = new ModelAndView("login");

        return mav;
    }

    //跳转到登录成功页面
    @RequestMapping("/loginsuccess.jhtml")
    public ModelAndView loginsuccess() throws Exception {
        ModelAndView mav = new ModelAndView("index");
        return mav;
    }

    @RequestMapping("/newPage.jhtml")
    public ModelAndView newPage() throws Exception {
        ModelAndView mav = new ModelAndView("newPage");
        return mav;
    }

    @RequestMapping("/newPageNotAdd.jhtml")
    public ModelAndView newPageNotAdd() throws Exception {
        ModelAndView mav = new ModelAndView("newPageNotAdd");
        return mav;
    }

    /** 
     * 验证用户名和密码 
     * @param String username,String password
     * @return 
     */  
    @RequestMapping(value="/checkLogin.json",method=RequestMethod.POST)  
    @ResponseBody  
    public String checkLogin(String username,String password)throws Exception {  
        Map<String, Object> result = new HashMap<String, Object>();
        ShiroUser user = tRoleMapper.queryRoleByUsername(username);
            UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtil.MD5(DecriptUtil.MD5(password)+user.getSalt()));  
            Subject currentUser = SecurityUtils.getSubject();  
            if (!currentUser.isAuthenticated()){
                //使用shiro来验证  
                token.setRememberMe(true);  
            } 
            String msg = null;
                try {
                    currentUser.login(token);//验证角色和权限  
                } catch (UnknownAccountException e) {
                    e.printStackTrace();
                    msg = e.getMessage();
                } catch (IncorrectCredentialsException e){
                    e.printStackTrace();
                    msg = "密码不匹配(生产环境中应该写:用户名和密码的组合不正确)";
                } catch (LockedAccountException e){
                    e.printStackTrace();
                    msg = e.getMessage();
                }
                if( msg==null){
                    result.put("success", true);
                }else{
                        result.put("success", false);
                        result.put("errorMsg", msg);
                }
                return JSONUtils.toJSONString(result); 
    }  

    /** 
     * 退出登录
     */  
    @RequestMapping(value="/logout.json",method=RequestMethod.POST)    
    @ResponseBody    
    public String logout() {   
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        Subject currentUser = SecurityUtils.getSubject();       
        currentUser.logout();    
        return JSONUtils.toJSONString(result);
    }  
}

10相关页面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<script src="/js/jquery.min.js"></script>
</head>
<body>
username: <input type="text" id="username"><br><br>  
password: <input type="password" id="password"><br><br>
<button id="loginbtn">登录</button>
</body>
<script type="text/javascript">
$('#loginbtn').click(function() {
    var param = {
        username : $("#username").val(),
        password : $("#password").val()
    };
    $.ajax({ 
        type: "post", 
        url: "<%=request.getContextPath()%>" + "/checkLogin.json", 
        data: param, 
        dataType: "json", 
        success: function(data) { 
            if(data.success == false){
                alert(data.errorMsg);
            }else{
                //登录成功
                window.location.href = "<%=request.getContextPath()%>" +  "/loginsuccess.jhtml";
            }
        },
        error: function(data) { 
            alert("调用失败...."); 
        }
    });
});
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_30553773/article/details/79255349