RBAC模型(Role-Based Access Control:基于角色的访问控制)模型是20世纪90年代研究出来的一种新模型,但其实在20世纪70年代的多用户计算时期,这种思想就已经被提出来,直到20世纪90年代中后期,RBAC才在研究团体中得到一些重视,并先后提出了许多类型的RBAC模型。
权限模型
RBAC表设计
create database rbac2206;
use rbac2206;
#用户表
create table users(
uid int primary key auto_increment,
username varchar(20) not null unique,
password varchar(20) not null,
tel varchar(11),
addr varchar(30)
);
#角色表
create table roles(
rid int primary key auto_increment,
rname varchar(20) not null unique ,
rdesc varchar(20)
);
#权限表
create table perms(
pid int primary key auto_increment,
pname varchar(20) not null unique,
pdesc varchar(20)
);
insert into users values(null, 'wukong', '888888', '188888888', 'huaguoshan');
insert into users values(null, 'wuneng', '777777', '177777777', 'gaolaozhuang');
insert into users values(null, 'wujing', '666666', '166666666', 'liushahe');
insert into users values(null, 'tangtang', '000000', '100000', 'changan');
insert into roles values(null, 'manager', 'manager desc');
insert into roles values(null, 'super manager', 'super manager desc');
insert into roles values(null, 'guest', 'guest desc');
insert into perms values(null, 'select', 'select desc');
insert into perms values(null, 'save', 'save desc');
insert into perms values(null, 'delete', 'delete desc');
insert into perms values(null, 'update', 'update desc');
#用户角色中间表
create table user_role(
uid int,
rid int,
primary key(uid, rid)
);
#角色权限中间表
create table role_perm(
rid int,
pid int,
primary key(rid, pid)
);
insert into user_role values(4, 1);
insert into user_role values(4, 2);
insert into user_role values(4, 3);
insert into user_role values(1, 1);
insert into user_role values(1, 3);
insert into user_role values(2, 3);
insert into user_role values(3, 3);
insert into role_perm values(2, 1);
insert into role_perm values(2, 2);
insert into role_perm values(2, 3);
insert into role_perm values(2, 4);
insert into role_perm values(1, 1);
insert into role_perm values(1, 4);
insert into role_perm values(3, 1);
select username, password, addr, tel,
rname, rdesc, pname, pdesc
from users u, roles r, perms p,
user_role ur, role_perm rp
where u.uid = ur.uid and r.rid = ur.rid
and p.pid = rp.pid and ur.rid = rp.rid
order by username;
select r.* from users u ,
user_role ur,
roles r
where u.uid = ur.uid and ur.rid = r.rid
and username = 'tangtang';
select distinct p.* from users u ,
user_role ur,
roles r,
role_perm rp,
perms p
where u.uid = ur.uid and ur.rid = r.rid
and r.rid = rp.rid and rp.pid = p.pid
and username = 'wuneng';
项目结构
创建Maven项目
1.导入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qfedu</groupId>
<artifactId>Days62Shiro02Web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<!--shiro-web依赖内置shiro-core-->
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!--c3po同druid一样为数据库连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--日志依赖框架-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--自动生成bean-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- maven项目是通过 maven-compiler-plugin 插件来对 Java 代码编译的,
如果不指定 JDK 版本,maven-compiler-plugin 会自动使用一个默认的版本 -->
<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插件 代替手动部署tomcat-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.创建db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/rbac?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8
user=java
pass=123456
编码
2.1创建数据库连接的工具类
Env.java
package com.util;
import java.io.IOException;
import java.util.Properties;
public class Env extends Properties {
private static Env instance = null;
private Env(){
try {
load(getClass().getResourceAsStream("/db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Env getInstance(){
if (instance == null){
instance = new Env();
}
return instance;
}
}
C3P0Util.java
package com.util;
import java.sql.*;
public class C3P0Util {
private final static String DB_URL = Env.getInstance().getProperty("url");
private final static String DB_DRIVER = Env.getInstance().getProperty("driver");
private final static String DB_USER = Env.getInstance().getProperty("user");
private final static String DB_PASS = Env.getInstance().getProperty("pass");
private static Connection conn = null;
static{
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn(){
try {
//原始连接方式
// conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
//c3P0连接池连接方式
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setJdbcUrl(DB_URL);
ds.setDriverClass(DB_DRIVER);
ds.setUser(DB_USER);
ds.setPassword(DB_PASS);
conn = ds.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
public static void closeAll(Connection conn, PreparedStatement ptst, ResultSet rs){
try {
if(rs != null){
rs.close();
rs = null;
}
if(ptst != null){
ptst.close();
ptst = null;
}
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
c3p0,dbcp与druid 三大数据库连接池的区别
1)DBCP
DBCP是一个依赖Jakarta commons-pool对象池机制的数据库连接池.DBCP可以直接的在应用程序中使用,Tomcat的数据源使用的就是DBCP。
2)c3p0
c3p0是一个开放源代码的JDBC连接池,它在lib目录中与Hibernate一起发布,包括了实现jdbc3和jdbc2扩展规范说明的Connection 和Statement 池的DataSources 对象。
3)Druid
阿里出品,淘宝和支付宝专用数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件库,一个 SQL Parser。支持所有JDBC兼容的数据库,包括Oracle、MySql、Derby、Postgresql、SQL Server、H2等等。Druid针对Oracle和MySql做了特别优化,比如Oracle的PS Cache内存占用优化,MySql的ping检测优化。Druid提供了MySql、Oracle、Postgresql、SQL-92的SQL的完整支持,这是一个手写的高性能SQL Parser,支持Visitor模式,使得分析SQL的抽象语法树很方便。简单SQL语句用时10微秒以内,复杂SQL用时30微秒。通过Druid提供的SQL Parser可以在JDBC层拦截SQL做相应处理,比如说分库分表、审计等。Druid防御SQL注入攻击的WallFilter就是通过Druid的SQL Parser分析语义实现的。
2.2创建实体类
Users.java
package com.pojo;
import lombok.Data;
import java.util.Set;
@Data
public class Users {
private int uid;
private String username;
private String password;
private String tel;
private String addr;
private Set<Roles> roles;
}
Roles.java
package com.pojo;
import lombok.Data;
import java.util.Set;
@Data
public class Roles {
private int rid;
private String rname;
private String rdesc;
private Set<Perms> perms;
}
Perms.java
package com.pojo;
import lombok.Data;
@Data
public class Perms {
private int pid;
private String pname;
private String pdesc;
}
2.3创建dao层
IuserDao.java
package com.dao;
import com.qfedu.pojo.Users;
public interface IUserDao {
//用户登录验证
Users login(String username, String password);
//通过用户名得到相应角色
List<Roles> getRolesByUsername(String username);
//通过用户名得到相应权限
List<Perms> getPermsByUsername(String username);
}
UserDaoImpl.java
package com.dao.impl;
import com.qfedu.dao.IUserDao;
import com.qfedu.pojo.Users;
import com.qfedu.util.C3P0Util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements IUserDao {
private Connection conn = null;
private PreparedStatement ptst = null;
private ResultSet rs = null;
@Override
public Users login(String username, String password) {
conn = C3P0Util.getConn();
String sql = "select * from users where username = ? and password =?";
try {
ptst = conn.prepareStatement(sql);
ptst.setString(1, username);
ptst.setString(2, password);
rs = ptst.executeQuery();
if (rs.next()){
int uid = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
String tel = rs.getString(4);
String addr = rs.getString(5);
Users u = new Users();
u.setUid(uid);
u.setUsername(name);
u.setPassword(pass);
u.setAddr(addr);
u.setTel(tel);
return u;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public List<Roles> getRolesByUsername(String username) {
conn = C3P0Util.getConn();
String sql = "select r.* from users u ,\n" +
" user_role ur,\n" +
" roles r\n" +
" where u.uid = ur.uid and ur.rid = r.rid\n" +
" and username = ?";
try {
ptst = conn.prepareStatement(sql);
ptst.setString(1, username);
rs = ptst.executeQuery();
List<Roles> roles = new ArrayList<>();
while (rs.next()){
int rid = rs.getInt(1);
String rname = rs.getString(2);
String rdesc = rs.getString(3);
Roles r = new Roles();
r.setRid(rid);
r.setRname(rname);
r.setRdesc(rdesc);
roles.add(r);
}
return roles;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public List<Perms> getPermsByUsername(String username) {
conn = C3P0Util.getConn();
String sql = "select distinct p.* from users u ,\n" +
" user_role ur,\n" +
" roles r,\n" +
" role_perm rp,\n" +
" perms p\n" +
"where u.uid = ur.uid and ur.rid = r.rid\n" +
" and r.rid = rp.rid and rp.pid = p.pid\n" +
" and username = ?";
try {
ptst = conn.prepareStatement(sql);
ptst.setString(1, username);
rs = ptst.executeQuery();
List<Perms> roles = new ArrayList<>();
while (rs.next()){
int rid = rs.getInt(1);
String rname = rs.getString(2);
String rdesc = rs.getString(3);
Perms r = new Perms();
r.setPid(rid);
r.setPname(rname);
r.setPdesc(rdesc);
roles.add(r);
}
return roles;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
2.4创建service层
接口
package com.qfedu.service;
import com.qfedu.pojo.Users;
public interface IUserService {
Users login(String username, String password);
List<Roles> getRolesByUserName(String username);
List<Perms> getPermsByUserName(String username);
}
接口实现类
package com.service.impl;
import com.qfedu.dao.IUserDao;
import com.qfedu.dao.impl.UserDaoImpl;
import com.qfedu.pojo.Users;
import com.qfedu.service.IUserService;
public class UserServiceImpl implements IUserService {
private IUserDao iud = new UserDaoImpl();
@Override
public Users login(String username, String password) {
return iud.login(username, password);
}
@Override
public List<Roles> getRolesByUserName(String username) {
return iud.getRolesByUsername(username);
}
@Override
public List<Perms> getPermsByUserName(String username) {
return iud.getPermsByUsername(username);
}
}
2.5编写controller层
package com.controller;
import com.qfedu.pojo.Users;
import com.qfedu.service.IUserService;
import com.qfedu.service.impl.UserServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
private IUserService ius = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Users u = ius.login(username, password);
if(u != null){
request.getRequestDispatcher("success.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
2.6编写页面
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/UserServlet">
username:<input type="text" name="username" /><p />
password:<input type="text" name="password" /><p />
<input type="submit" value="submit" /><p />
</form>
</body>
</html>
web整合Shiro
3.1创建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_4_0.xsd"
version="4.0">
<!--使用Shiro必须要有监听器-->
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<!--过滤器过滤请求-->
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--错误代码错误页面显示-->
<error-page>
<error-code>401</error-code>
<location>/errorpage.jsp</location>
</error-page>
</web-app>
说明:EnvironmentLoaderListener里面包含了SecurityManager对象和ServletContext当中注册shiro, ShiroFilter让所有的请求都经过ShiroFilter过滤器
3.2创建shiro.ini文件
[main]
mr=com.shiro.MyRealm
authc=org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authc.loginUrl=/login.jsp
securityManager.realm=$mr
[urls]
/index.html = anon
#/user/create = anon
#/user/** = authc
#/admin/** = authc, roles[administrator]
#/rest/** = authc, rest
#/remoting/rpc/** = authc, perms["remote:invoke"]
/superManager.jsp=authc, roles[super manager]
/manager.jsp=authc, roles[manager]
/guest.jsp=authc, roles[guest]
/select.jsp=authc, perms[select]
/save.jsp=authc, perms[save]
/delete.jsp=authc, perms[delete]
/update.jsp=authc, perms[update]
authc代表认证用户, roles[xxx]代表拥有xxx角色的用户, perms[xxx]代表拥有xxx权限的用户, anon匿名用户
3.3编写controller层
UserSelect.java
package com.controller;
import com.pojo.Users;
import com.service.IUserService;
import com.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
private IUserService ius = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
//
/shiro的调用/
// IniSecurityManagerFactory()默认加载shiro.ini文件
IniSecurityManagerFactory factory = new IniSecurityManagerFactory();
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
// 登录功能,真正实现用户的认证功能
subject.login(token);
System.out.println(subject.isAuthenticated());
// System.out.println(subject.hasRole("manager"));
//
// subject.checkPermissions("select", "update");
response.sendRedirect("success.jsp");
} catch (AuthenticationException e) {
e.printStackTrace();
}
//
// Users u = ius.login(username, password);
//
// if(u != null){
// request.getRequestDispatcher("success.jsp").forward(request,response);
// }
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
3.4编写自己的Realm
Realm:域,Realm 充当了 Shiro 与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro 会从应用配置的 Realm 中查找用户及其权限信息。从这个意义上讲,Realm 实质上是一个安全相关的 DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给 Shiro 。当配置 Shiro时,你必须至少指定一个 Realm ,用于认证和(或)授权。配置多个 Realm 是可以的,但是至少需要一个。
Shiro 内置了可以连接大量安全数据源(又名目录)的 Realm,如 LDAP、关系数据库(JDBC)、类似 INI 的文本配置资源以及属性文件等。如果缺省的 Realm 不能满足需求,你还可以插入代表自定义数据源的自己的 Realm 实现。
MyRealm.java
package com.shiro;
import com.pojo.Perms;
import com.pojo.Roles;
import com.pojo.Users;
import com.service.IUserService;
import com.service.impl.UserServiceImpl;
import org.apache.shiro.authc.*;
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 java.util.List;
public class MyRealm extends AuthorizingRealm {
private IUserService ius = new UserServiceImpl();
/**
* 授权方法,含有的参数是身份集合,使用身份集合就可以获取用户账户信息
*
* @param principalCollection
* @return AuthorizationInfo接口对象
* 剩余的事情就交给了shiro的会话管理器来自动完成
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = getAvailablePrincipal(principalCollection).toString();
System.out.println(username + "---------------");
List<Roles> roles = ius.getRolesByUserName(username);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Roles r : roles) {
info.addRole(r.getRname());
}
List<Perms> perms = ius.getPermsByUserName(username);
for (Perms p : perms) {
info.addStringPermission(p.getPname());
}
return info;
}
/**
* 认证方法,用户在输入了自己的用户名和密码信息之后,点击提交按钮,即通过subject的login(token)方法,
* 将请求传递给当前方法,进行认证的处理
* @param authenticationToken,含有用户名和密码参数的token对象,可以获取到用户名(身份)和密码(凭证)信息
* @return AuthenticationInfo接口对象
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
char[] passchar = token.getPassword(); // 为了保证密码的安全性,java几乎将密码都设置成立字符数组
String password = new String(passchar);
System.out.println(username + "\t" + password);
Users u = ius.login(username, password);
if(u != null){
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
return info;
}
return null;
}
}
以前传统方式是controller->service->dao,dao与数据库交互完成crud功能,返回给dao,返回给service,返回给controller
shiro与web的整合,则是controller->shiro->service->dao
3.5编写页面
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<form method="post" action="/UserServlet">
username:<input type="text" name="username" /><p />
password:<input type="text" name="password" /><p />
<input type="submit" value="submit" /><p />
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
<title>success</title>
</head>
<body>
<shiro:guest>
Hi there! Please <a href="login.jsp">Login</a> or <a href="signup.jsp">Signup</a> today!
</shiro:guest>
<hr />
<shiro:user>
Welcome back <shiro:principal/>! Not <shiro:principal/>? Click <a href="login.jsp">here<a> to login.
</shiro:user>
success
<hr/>
super <shiro:hasRole name="super manager">yes</shiro:hasRole><p />
manager <shiro:hasRole name="manager">yes</shiro:hasRole><p />
guest <shiro:hasRole name="guest">yes</shiro:hasRole><p />
select <shiro:hasPermission name="select">yes</shiro:hasPermission><p />
delete <shiro:hasPermission name="delete">yes</shiro:hasPermission><p />
update <shiro:hasPermission name="update">yes</shiro:hasPermission><p />
save <shiro:hasPermission name="save">yes</shiro:hasPermission><p />
</body>
</html>
errorpage.jsp(其他的页面同以下页面未编写内容)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>errorpage</h1>
</body>
</html>
3.6实现效果
- 在未登录的情况下,无法访问登录页以外的其他页面,会自动跳转到login.jsp页面
- 以不同用户登录后有不同的访问权限(guest manager supermanager),如果没有页面的访问权限访问会跳入到错误页面
- 以不同用户登录有不同的操作权限(save update delete select),如果没有相应的操作权限,进入错误页面。
- 不同用户登录成功后,访问success.jsp页面会动态显示用户的信息