1.什么是shiro
apache shiro是一个强大的易用的java安全框架,提供了认证,授权,加密和会话管理功能,可为任何应用提供安全保障-从命令行应用,移动应用到大型网络及企业应用
2.为什么要学习shiro
1.shiro已经将安全认证相关的功能抽取出来组成一个框架,使用shiro就可以非常快速的完成认证、授权等功能的开发,降低系统开发成本。
2.shiro使用广泛,shiro可以运行在web应用、非web应用、集群分布式应用中越来越多的用户开始使用shiro。
3.java领域中spring security也是一个开源的权限管理框架,但是spring security依赖spring运行,而shiro就相对独立,最主要因为shiro使用简单、灵活。
3.shiro整体架构图
4.架构图分析
图中的subject就是请求主体。subject请求都交给Security Manager进行处理。Security Manager是暴露给主体请求的唯一一个接口。
在Security Manager 中又有Authenticator、Authorized、
SessionManager、Realm、SessionDAO和Cache Manager模块。下面会详细介绍这些模块的作用。
(1)Subject
Subject即主体,外部应用与 subject进行交互,subject记录了当前操作用户,将用户的理解为当前操作的主体,可以是通过浏览器请求的用户,也可能是一个运行的程序。
Subject在shiro中是一个接口,接口中定义了很多认证授权的方法,外部程序通过subject进行认证授权,而subject通过Security Manager安全管理器进行认证授权。
(2)Security Manager
Sercurity Manager即安全管理器,对所有的subject进行管理,它是shiro的核心,负责对所有的subject进行安全管理。通过Security Manager可以完成对shiro的认证、授权等,但是实质上Security Manager是通过Authenticator进行认证、通过Authorizer进行授权、通过sessionManager进行会话管理等。
SecurityManager是一个接口,继承了Authenticator、Authorizer、SessionManager这三个接口。
(3)Authenticator
Authenticator即认证器,对subject身份进行认证,Authenticator是一个接口,shiro提供了ModularRealmAuthenticator实现类,通过ModularRealmAuthenticator基本上可以满足大多数的需求,也可以自定义认证器。
(4)Authorizer
Authorizer即授权器,subject认证通过后,在访问功能时需要通过授权器判断用户是否有此功能的操作权限。
(5)Realm
realm即域,相当于DataSource数据源,securityManager进行安全认证需要通过realm获取用户权限数据,比如:如果用户身份信息存储在数据库那么realm就需要从数据库获取用户身份信息。
注意: 不要把realm理解成只是从数据源取数据,在realm中还有认证授权校验相关的代码。
(6)Session Manager
sessionManager 即会话管理,shiro框架提供了一套会话管理,它不依赖web容器的session,所以shiro可以使用在非web环境中,也可以将分布式应用的会话集中在一点管理,此特性可使它实现单点登录。
(7)sessionDAO
sessionDAO即会话管理DAO,是对session会话管理操作的一套接口,比如要将session存储到数据库,可以使用jdbc将会话存储到数据库。
(8)CacheManager
CacheManager即缓存管理,将用户权限存储在缓存,可以提高性能。
(9)Crypography
crypography即密码管理,shiro提供了一套加密/解密的组件,方便开发。提供了常用的散列、加/解密算法。
5.下面是我的目录结构
6.代码展示
(1)pom.xml依赖
<properties>
<!--统一管理spring所有的版本-->
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--spring的单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--serlvet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8889</port>
</configuration>
</plugin>
</plugins>
</build>
(2)shiro-spring.xml代码
<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">
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"></property>
</bean>
<bean class="com.it.shiro.MyRealm" id="myRealm"></bean>
<bean class="org.apache.shiro.spring.LifecycleBeanPostProcessor" id="lifecycleBeanPostProcessor"></bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<property name="filterChainDefinitions">
<value>
/login.jsp=anon
/main.jsp=authc
/manager.jsp=roles[manager]
/guest.jsp=roles[guest]
</value>
</property>
</bean>
</beans>
(3).spring-mvc.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:tx="http://www.springframework.org/schema/tx"
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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:db.properties"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<context:component-scan base-package="com.it.controller"/>
<context:component-scan base-package="com.it.service"/>
<context:component-scan base-package="com.it.dao"/>
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${url}"></property>
<property name="driverClassName" value="${driver}"></property>
<property name="username" value="${aaa}"></property>
<property name="password" value="${bbb}"></property>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sf">
<property name="dataSource" ref="ds"></property>
<property name="typeAliasesPackage" value="com.it.entity"></property>
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.it.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sf"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
</beans>
(4).web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!--
将过滤器的生命周期从出生到死亡完全交给Spring来管理
-->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests. Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain: -->
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(5).实体类的代码
@Data
public class Permission implements Serializable {
private static final long serialVersionUID = 581645870054218482L;
private Integer pid;
private String pname;
private String pdesc;
private Set<Role> rs;
}
@Data
public class Role implements Serializable {
private static final long serialVersionUID = -74163700661732397L;
private Integer rid;
private String rname;
private String rdesc;
private Set<Permission> ps;
}
@Data
public class User implements Serializable {
private static final long serialVersionUID = 617289138502785533L;
private Integer uid;
private String username;
private String password;
private String tel;
private String addr;
}
(6).dao层代码
import com.it.entity.Permission;
import com.it.entity.Role;
import com.it.entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserDao {
User login(@Param("username") String username, @Param("password")String password);
List<Role> getRolesByUsername(String username);
List<Permission> getPermissionsByUsername(String username);
}
(7).service层代码
import java.util.List;
import com.it.entity.Permission;
import com.it.entity.Role;
import com.it.entity.User;
public interface UserService {
User login(String username, String password);
List<Role> getRolesByUsername(String username);
List<Permission> getPermissionsByUsername(String username);
}
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public User login(String username, String password) {
return userDao.login(username,password);
}
@Override
public List<Role> getRolesByUsername(String username) {
return userDao.getRolesByUsername(username);
}
@Override
public List<Permission> getPermissionsByUsername(String username) {
return userDao.getPermissionsByUsername(username);
}
}
(8).自定义的MyRealm
mport javax.annotation.Resource;
public class MyRealm extends AuthorizingRealm {
@Resource
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
System.out.println(principalCollection + "000000");
String username = getAvailablePrincipal(principalCollection).toString();
List<Role> roles = userService.getRolesByUsername(username);
for (Role role : roles) {
info.addRole(role.getRname());
}
List<Permission> permissions = userService.getPermissionsByUsername(username);
for (Permission permission : permissions) {
info.addStringPermission(permission.getPname());
}
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
AuthenticationInfo info = null;
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
char[] pass = token.getPassword();
String password = new String(pass);
User user = userService.login(username, password);
if(user != null && user.getUid() != 0){
info = new SimpleAuthenticationInfo(username,password,getName());
}
return info;
}
}
(9).控制层代码
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
System.out.println(111);
subject.login(token);
System.out.println(000);
return "main.jsp";
} catch (AuthenticationException e) {
System.out.println(222);
e.printStackTrace();
return "login.jsp";
}
}
}
(10)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 namespace="com.it.dao.UserDao">
<select id="login" resultType="user">
select * from user where username = #{username} and password = #{password}
</select>
<select id="getRolesByUsername" resultType="role">
SELECT r.* FROM user u
INNER JOIN user_role ur on u.uid = ur.uid
INNER JOIN Role r on r.rid = ur.rid
WHERE u.username =#{username};
</select>
<select id="getPermissionsByUsername" resultType="permission">
SELECT p.* FROM user u
INNER JOIN user_role ur on u.uid = ur.uid
INNER JOIN Role r on r.rid = ur.rid
INNER JOIN role_perms rp on r.rid = rp.rid
INNER JOIN permission p on p.pid = rp.pid
WHERE u.username = #{username}
</select>
</mapper>
(11).我这里只给出main.jsp代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
<title>main</title>
</head>
<body>
<h1>this is main page.</h1>
<shiro:authenticated>i am login successfully.</shiro:authenticated><p />
<shiro:hasRole name="manager">i am a manager</shiro:hasRole><p />
<shiro:hasRole name="guest">i am a guest</shiro:hasRole><p />
<shiro:user>
welcome back <shiro:principal/>!
Not <shiro:principal/>? Click <a href="index.html">here</a> to login
</shiro:user><p />
<shiro:hasPermission name="select">i can select</shiro:hasPermission><p />
<shiro:hasPermission name="delete">i can delete</shiro:hasPermission><p />
</body>
</html>
(12).这里为了方便这里给我的sql脚本
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50520
Source Host : localhost:3306
Source Database : rbac
Target Server Type : MYSQL
Target Server Version : 50520
File Encoding : 65001
Date: 2020-04-19 10:11:00
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`pname` varchar(20) NOT NULL,
`pdesc` varchar(20) DEFAULT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES ('1', 'select', 'select desc');
INSERT INTO `permission` VALUES ('2', 'insert', 'insert desc');
INSERT INTO `permission` VALUES ('3', 'delete', 'delete desc');
INSERT INTO `permission` VALUES ('4', 'update', 'update desc');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`rid` int(11) NOT NULL AUTO_INCREMENT,
`rname` varchar(20) NOT NULL,
`rdesc` varchar(20) DEFAULT NULL,
PRIMARY KEY (`rid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'manager', 'manager desc');
INSERT INTO `role` VALUES ('2', 'guest', 'guest desc');
-- ----------------------------
-- Table structure for role_perms
-- ----------------------------
DROP TABLE IF EXISTS `role_perms`;
CREATE TABLE `role_perms` (
`rid` int(11) NOT NULL,
`pid` int(11) NOT NULL,
PRIMARY KEY (`rid`,`pid`),
KEY `FK_Reference_4` (`pid`),
CONSTRAINT `FK_Reference_3` FOREIGN KEY (`rid`) REFERENCES `role` (`rid`),
CONSTRAINT `FK_Reference_4` FOREIGN KEY (`pid`) REFERENCES `permission` (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of role_perms
-- ----------------------------
INSERT INTO `role_perms` VALUES ('1', '1');
INSERT INTO `role_perms` VALUES ('2', '1');
INSERT INTO `role_perms` VALUES ('1', '2');
INSERT INTO `role_perms` VALUES ('2', '2');
INSERT INTO `role_perms` VALUES ('1', '3');
INSERT INTO `role_perms` VALUES ('1', '4');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`tel` varchar(20) NOT NULL,
`addr` varchar(50) DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'wukong', '888888', '13333333333', 'huaguoshan');
INSERT INTO `user` VALUES ('2', 'bajie', '888888', '13333333333', 'gaolaozhuang');
INSERT INTO `user` VALUES ('3', 'shanseng', '888888', '13333333333', 'liushanhe');
INSERT INTO `user` VALUES ('4', 'tangtang', '888888', '13333333333', 'datang');
INSERT INTO `user` VALUES ('5', 'bailongma', '888888', '1111111111', 'donghailonggong');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`uid` int(11) NOT NULL,
`rid` int(11) NOT NULL,
PRIMARY KEY (`uid`,`rid`),
KEY `FK_Reference_2` (`rid`),
CONSTRAINT `FK_Reference_1` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`),
CONSTRAINT `FK_Reference_2` FOREIGN KEY (`rid`) REFERENCES `role` (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1');
INSERT INTO `user_role` VALUES ('4', '1');
INSERT INTO `user_role` VALUES ('2', '2');
INSERT INTO `user_role` VALUES ('3', '2');