上一篇搭建Maven、SSM框架详细步骤,然后本文在此基础上,集成shiro框架
文章目录
一、创建数据库(数据库名:shiro,多对多关系)
- 运行 shiro.sql 脚本添加数据库
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50528
Source Host : localhost:3306
Source Database : shiro
Target Server Type : MYSQL
Target Server Version : 50528
File Encoding : 65001
Date: 2019-07-28 21:21:26
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`perid` int(11) NOT NULL AUTO_INCREMENT,
`pername` varchar(255) DEFAULT NULL,
`percode` varchar(255) DEFAULT NULL,
PRIMARY KEY (`perid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES ('1', '用户查询', 'user:query');
INSERT INTO `permission` VALUES ('2', '用户添加', 'user:add');
INSERT INTO `permission` VALUES ('3', '用户修改', 'user:update');
INSERT INTO `permission` VALUES ('4', '用户删除', 'user:delete');
INSERT INTO `permission` VALUES ('5', '导出用户', 'user:export');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`roleid` int(11) NOT NULL AUTO_INCREMENT,
`rolename` varchar(255) DEFAULT NULL,
PRIMARY KEY (`roleid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', '超级管理员');
INSERT INTO `role` VALUES ('2', 'CEO');
INSERT INTO `role` VALUES ('3', '保安');
-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
`perid` int(255) DEFAULT NULL,
`roleid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role_permission
-- ----------------------------
INSERT INTO `role_permission` VALUES ('1', '1');
INSERT INTO `role_permission` VALUES ('2', '1');
INSERT INTO `role_permission` VALUES ('3', '1');
INSERT INTO `role_permission` VALUES ('4', '1');
INSERT INTO `role_permission` VALUES ('1', '2');
INSERT INTO `role_permission` VALUES ('2', '2');
INSERT INTO `role_permission` VALUES ('3', '2');
INSERT INTO `role_permission` VALUES ('1', '3');
INSERT INTO `role_permission` VALUES ('5', '3');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`userpwd` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user md5加密 盐是姓名加地址,散列2次
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '639ffb0cbcca39d4fff8348844b1974e', '男', '武汉');
INSERT INTO `user` VALUES ('2', 'lisi', '0d303fa8e2e2ca98555f23a731a58dd9', '女', '北京');
INSERT INTO `user` VALUES ('3', 'wangwu', '473c41db9af5cc0d90e7adfd2b6d9180', '女', '成都');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`userid` int(11) DEFAULT NULL,
`roleid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1');
INSERT INTO `user_role` VALUES ('2', '2');
INSERT INTO `user_role` VALUES ('3', '3');
二、修改pom.xml引入shiro包
<shiro.version>1.4.1</shiro.version>
<!-- 依赖shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
三、创建domain下的类,mapper接口,mapper.xml 文件
1.创建User类、 UserMapper接口、UserMapper.xml
2.创建Role类、 RoleMapper接口、RoleMapper.xml
3.创建Permission类、PermissionMapper接口、 PermissionMapper.xml
以user为例
- 创建User类、
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer userid;
private String username;
private String userpwd;
private String sex;
private String address;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd == null ? null : userpwd.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
}
- UserMapper接口、
public interface UserMapper {
int deleteByPrimaryKey(Integer userid);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userid);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
/**
* 根据用户名查询用户
* @param username
* @return
*/
User queryUserByUserName(@Param("username")String username);
}
- 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="包.mapper.UserMapper">
<resultMap id="BaseResultMap" type="包.domain.User">
<id column="userid" jdbcType="INTEGER" property="userid" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="userpwd" jdbcType="VARCHAR" property="userpwd" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="address" jdbcType="VARCHAR" property="address" />
</resultMap>
<sql id="Base_Column_List">
userid, username, userpwd, sex, address
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where userid = #{userid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where userid = #{userid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="包.domain.User">
insert into user (userid, username, userpwd,
sex, address)
values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{userpwd,jdbcType=VARCHAR},
#{sex,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="包.domain.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userid != null">
userid,
</if>
<if test="username != null">
username,
</if>
<if test="userpwd != null">
userpwd,
</if>
<if test="sex != null">
sex,
</if>
<if test="address != null">
address,
</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="userpwd != null">
#{userpwd,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=VARCHAR},
</if>
<if test="address != null">
#{address,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="包.domain.User">
update user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="userpwd != null">
userpwd = #{userpwd,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="address != null">
address = #{address,jdbcType=VARCHAR},
</if>
</set>
where userid = #{userid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="包.domain.User">
update user
set username = #{username,jdbcType=VARCHAR},
userpwd = #{userpwd,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
address = #{address,jdbcType=VARCHAR}
where userid = #{userid,jdbcType=INTEGER}
</update>
<!-- 根据用户名查询用户 -->
<select id="queryUserByUserName" resultMap="BaseResultMap">
select * from user where username=#{username}
</select>
</mapper>
四、创建ActiverUser
五、创建UserRealm
public class UserRealm extends AuthorizingRealm {
@Override
public String getName() {
return this.getClass().getSimpleName();
}
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permssionService;
/**
* 完成认证的方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
Object credentials = token.getCredentials();// 用户登陆时传过来的
System.out.println(Arrays.toString((char[]) credentials));
// 根据用户名查询用户是否存在
User user = this.userService.queryUserByUserName(username);
// 返回null说明用户不存在
if (null != user) {
// 根据用户名去查询用户拥有哪些角色
List<String> roles = roleService.queryRolesByUserId(user.getUserid());
// 根据用户名查询用户拥有哪些权限
List<String> permissions = this.permssionService.queryPermissionsByUserId(user.getUserid());
ActiveUser activeUser = new ActiveUser(user, roles, permissions);
/**
* 参数1 用户身份 参数2 用户在数据库里面存放的密码 参数3 当前类名
*/
// SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activeUser,
// user.getPassword(), this.getName());
/**
* 参数1:传到doGetAuthorizationInfo里面getPrimaryPrincipal()的对象或者subject.getPrincipal()
* 参数2:hashedCredentials 加密之后的密码 参数3:credentialsSalt 盐
*/
ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername()+user.getAddress());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, user.getUserpwd(), credentialsSalt,
this.getName());
return info;
}
return null;
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 根据用户名去查询用户拥有哪些角色
List<String> roles = activeUser.getRoles();
if (null != roles && roles.size() > 0) {
// 添加角色
info.addRoles(roles);
}
// 根据用户名查询用户拥有哪些权限
List<String> permissions = activeUser.getPermissions();
// 添加权限
if (null != permissions && permissions.size() > 0) {
// 添加角色
info.addStringPermissions(permissions);
}
return info;
}
}
六、修改web.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>
<init-param>
<!-- 这里的shrioFilter必须和application-shrio.xml里面的 过滤器ID一致 -->
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
<!-- 配置shiro的代理过滤器 结束 -->
七、创建application-shiro.xml 并在applicationContext.xml 引入(import)
- 创建application-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"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- 声明凭证匹配器 -->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 注入加密方式 -->
<property name="hashAlgorithmName" value="md5"></property>
<!-- 注入散列次数 -->
<property name="hashIterations" value="2"></property>
</bean>
<!-- 声明userRealm -->
<bean id="userRealm" class="包.realm.UserRealm">
<!-- 注入凭证匹配器 -->
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
<!-- 声明一个cookie的对象 -->
<bean id="cookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe"></constructor-arg>
<!-- 只有http请求才会生效 -->
<property name="httpOnly" value="true"></property>
<!-- 设置cookie的存活时间 单位是秒 -->
<property name="maxAge" value="604800"></property>
</bean>
<!-- 声明一个cookie管理器 -->
<bean id="cookieManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie" ref="cookie"></property>
</bean>
<!-- 声明安全管理器 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 注入realm -->
<property name="realm" ref="userRealm"></property>
<!-- 注入一个记住我的管理器 -->
<property name="rememberMeManager" ref="cookieManager"></property>
</bean>
<!-- 声明记住我的自定义过滤器对象 -->
<bean id="rememberMe" class="包.filter.RememberMeFilter"></bean>
<!-- 配置shrio的过滤器链 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 注入安全管理器 -->
<property name="securityManager" ref="securityManager"></property>
<!-- 注入如果没认证 跳转的页面 -->
<property name="loginUrl" value="/index.jsp"></property>
<!-- 未授权的跳转页 -->
<property name="unauthorizedUrl" value="login/toUnauthorized.action"></property>
<!-- 注入自定义的过滤器 -->
<property name="filters">
<map>
<entry key="rememberMe" value-ref="rememberMe"></entry>
</map>
</property>
<property name="filterChainDefinitions">
<value>
<!-- 放行系统首页 -->
/index.jsp*=anon
<!-- 放行跳转到登陆页面的地 -->
/login/toLogin*=anon
<!-- 放行登陆的方法 -->
/login/login*=anon
<!-- 其它的页面都要认证 -->
/**=rememberMe,user
/*=authc
/*/*=authc
</value>
</property>
</bean>
</beans>
- 在applicationContext.xml 引入(import)
八、创建 包.listener 下面 AppListener.java
@WebListener
public class AppListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
context.setAttribute("ctx", context.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}