Shiro是一款安全工具插件,较Security轻量级,配置简单易上手。
.既然是登录验证,定然少不了数据库表,一般权限表的设计是五张表:用户表、权限表、许可、用户-权限、权限-许可
- 用户表
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`salt` varchar(255) DEFAULT NULL,
`state` tinyint(4) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=MyISAM AUTO_INCREMENT=47 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_info
-- ----------------------------
INSERT INTO `user_info` VALUES ('1', '管理员', 'd3c59d25033dbf980d29554025c23a75', '8d78869f470951332959580424d4bf4f', '0', 'admin');
- **权限表**
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(11) NOT NULL,
`available` bit(1) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`role` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', '', '管理员', 'admin');
INSERT INTO `sys_role` VALUES ('2', '', 'VIP会员', 'vip');
- **许可表**
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` int(11) NOT NULL,
`available` bit(1) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`parent_id` bigint(20) DEFAULT NULL,
`parent_ids` varchar(255) DEFAULT NULL,
`permission` varchar(255) DEFAULT NULL,
`resource_type` enum('menu','button') DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES ('1', '', '用户管理', '0', '0/', 'userInfo:view', 'menu', 'userInfo/userList');
INSERT INTO `sys_permission` VALUES ('2', '', '用户添加', '1', '0/1', 'userInfo:add', 'button', 'userInfo/userAdd');
INSERT INTO `sys_permission` VALUES ('3', '', '用户删除', '1', '0/1', 'userInfo:del', 'button', 'userInfo/userDel');
- *用户-权限
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`role_id` int(11) NOT NULL,
`uid` int(11) NOT NULL,
KEY `FKgkmyslkrfeyn9ukmolvek8b8f` (`uid`),
KEY `FKhh52n8vd4ny9ff4x9fb8v65qx` (`role_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('1', '1');
- 权限-许可
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`role_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL,
KEY `FKomxrs8a388bknvhjokh440waq` (`permission_id`),
KEY `FK9q28ewrhntqeipl1t04kh1be7` (`role_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES ('1', '1');
INSERT INTO `sys_role_permission` VALUES ('1', '2');
- 我们先来看下pom.xml
<?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.springboot</groupId>
<artifactId>shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>shiro</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<!-- 版本号可以不用指定,Spring Boot会选用合适的版本 -->
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 生成实体类及其映射文件
根据数据库文件我们知道有三张主表,两张辅表,我们只要生成主表的相关信息就行(为了方便我把三种数据库的配置信息都写上了)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--<classPathEntry location="E:\maven_repo\repository\com\oracle\ojdbc6\11.2.0.4\ojdbc6-11.2.0.4.jar"/>-->
<!--<classPathEntry location="F:/ojdbc7-12.1.0.1.jar"/>-->
<!--<classPathEntry location="F:/sqljdbc4-4.0.jar"/>-->
<classPathEntry location="F:/mysql-connector-java-5.1.44.jar"/>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"-->
<!--connectionURL="jdbc:oracle:thin:@//192.168.6.121:1521/orcl"-->
<!--userId="scott"-->
<!--password="tiger">-->
<!--</jdbcConnection>-->
<!--<jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"-->
<!--connectionURL="jdbc:sqlserver://192.168.4.182:1433;DatabaseName=VCLogAlarm"-->
<!--userId="sa"-->
<!--password="PF,123">-->
<!--</jdbcConnection>-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.6.121:3306/test"
userId="root"
password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.springboot.shiro.model"
targetProject="src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="resources\mapper"
targetProject="src\main">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.springboot.shiro.mapper"
targetProject="src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="user_info" domainObjectName="User"/>
<table tableName="sys_role" domainObjectName="Role"/>
<table tableName="sys_permission" domainObjectName="Permission"/>
</context>
</generatorConfiguration>
- 生成之后就是这样的
不要忘记辅表哦
user
private Integer uid;
private String name;
private String password;
private String salt;
private Byte state;
private String username;
private List<Role> roleList;// 一个用户具有多个角色
/**
* 密码盐.
* @return
*/
public String getCredentialsSalt(){
return this.username+this.salt;
}
//省略 Getter、Setter
role
private Integer id;
private Boolean available;
private String description;
private String role;
private List<Permission> permissions;
private List<User> userInfos;// 一个角色对应多个用户
//省略 Getter、Setter
Permission
private Integer id;
private Boolean available;
private String name;
private Long parentId;
private String parentIds;
private String permission;
private String resourceType;
private String url;
private List<Role> roles;
//省略 Getter、Setter
这样主表和辅表都搞定了
接下来到了我们的主角shiro的配置了
package com.springboot.shiro.configurator;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 15:40 2018/5/29
*/
/**
* Shiro 配置
*
Apache Shiro 核心通过 Filter 来实现,就好像SpringMvc 通过DispachServlet 来主控制一样。
既然是使用 Filter 一般也就能猜到,是通过URL规则来进行过滤和权限校验,所以我们需要定义一系列关于URL的规则和访问权限。
*
* @author Angel(QQ:412887952)
* @version v.0.1
*/
@Configuration
public class ShiroConfiguration {
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shiroFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//拦截器.
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/favicon.ico", "anon");
// filterChainDefinitionMap.put("/css/**", "anon");
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
//<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
//<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
filterChainDefinitionMap.put("/**", "authc");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.html"页面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的链接
shiroFilterFactoryBean.setSuccessUrl("/index");
//未授权界面;
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* 身份认证realm;
* (这个需要自己写,账号密码校验;权限等)
* @return
*/
@Bean
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); //设置加密规则
return myShiroRealm;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置Realm
securityManager.setRealm(myShiroRealm());
//注入缓存管理器
// securityManager.setCacheManager(ehCacheManager());//这个如果执行多次,也是同样的一个对象;
//注入记住我管理器
// securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
/**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
* 所以我们需要修改下doGetAuthenticationInfo中的代码)
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""))
return hashedCredentialsMatcher;
}
}
package com.springboot.shiro.configurator;
import com.springboot.shiro.common.Logs;
import com.springboot.shiro.model.Permission;
import com.springboot.shiro.model.Role;
import com.springboot.shiro.model.User;
import com.springboot.shiro.service.UserService;
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 org.apache.shiro.util.ByteSource;
import javax.annotation.Resource;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 16:16 2018/5/30
*/
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Logs.LOGGER.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principals.getPrimaryPrincipal();
for (Role role :user.getRoleList() ){
authorizationInfo.addRole(role.getRole());
for (Permission permission :role.getPermissions()){
authorizationInfo.addStringPermission(permission.getPermission());
}
}
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
Logs.LOGGER.info("开始身份认证:===》 MyShiroRealm.doGetAuthenticationInfo()");
//获取用户的输入的账号.
String username = (String)token.getPrincipal();
Logs.LOGGER.info("用户信息"+token.getCredentials());
//通过username从数据库中查找 User对象,如果找到,没找到.
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
User user = userService.findByUsername(username);
Logs.LOGGER.info("----->>user=::"+user);
if(user == null){
return null;
}
if (user.getState() == 1){ //账户冻结
throw new LockedAccountException();
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user, //用户名
user.getPassword(), //密码
ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;
}
}
注释差不多都有 当然你也可以自由扩展下,接下来服务层了
- Service
package com.springboot.shiro.service;
import com.springboot.shiro.common.ServiceException;
import com.springboot.shiro.model.User;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 10:10 2018/6/6
*/
public interface UserService {
User findByUsername(String username) throws ServiceException;
}
- ServiceImpl
package com.springboot.shiro.service;
import com.springboot.shiro.common.Logs;
import com.springboot.shiro.common.ServiceException;
import com.springboot.shiro.mapper.UserMapper;
import com.springboot.shiro.model.User;
import com.springboot.shiro.model.UserExample;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 10:10 2018/6/6
*/
@Service
public class UserImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public User findByUsername(String username) throws ServiceException {
Logs.LOGGER.info("登录 ===》》 UserImpl.findByUsername()");
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo(username);
List<User> users = userMapper.selectByExample(example);
User user = users.get(0);
return user;
}
}
这里没有什么需要重点讲的,Logs控制台日志在Common包里
package com.springboot.shiro.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 10:08 2018/6/6
*/
public class Logs {
public static final Logger LOGGER = LoggerFactory.getLogger(Logs.class);
}
ServiceException的统一异常
package com.springboot.shiro.common;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 11:11 2018/5/31
*/
public class ServiceException extends RuntimeException {
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public ServiceException(String message, int code) {
super(message);
this.code = code;
}
public ServiceException(String message) {
super(message);
}
}
接下来就是controller层了
package com.springboot.shiro.app.controller;
import com.springboot.shiro.common.Logs;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @Author: YafengLiang
* @Description:
* @Date: Created in 10:16 2018/6/6
*/
@Controller
public class PageController {
@RequestMapping(value = {"/","/index"})
public String index(){
return "index";
}
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping(value = "/login")
public String login(HttpServletRequest request, Map<String, Object> map){
Logs.LOGGER.info("PageController.login()");
// 登录失败从request中获取shiro处理的异常信息。
// shiroLoginFailure:就是shiro异常类的全类名.
String exception = (String) request.getAttribute("shiroLoginFailure");
Logs.LOGGER.info("Exception::"+exception);
String msg = "";
if (exception!= null){
if (UnknownAccountException.class.getName().equals(exception)) {
System.out.println("UnknownAccountException -- > 账号不存在:");
msg = "UnknownAccountException -- > 账号不存在:";
} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
System.out.println("IncorrectCredentialsException -- > 密码不正确:");
msg = "IncorrectCredentialsException -- > 密码不正确:";
} else if ("kaptchaValidateFailed".equals(exception)) {
System.out.println("kaptchaValidateFailed -- > 验证码错误");
msg = "kaptchaValidateFailed -- > 验证码错误";
} else {
msg = "else >> "+exception;
System.out.println("else -- >" + exception);
}
}
map.put("msg",msg);
// 此方法不处理登录成功,由shiro进行处理.
return "/login";
}
}
application的信息,使用的是yml格式
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.6.121:3306/test
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
idle-timeout: 60000
max-lifetime: 1800000
connection-timeout: 60000
maximum-pool-size: 5
minimum-idle: 1
thymeleaf:
encoding: UTF-8
cache: false
mode: HTML
mybatis:
mapper-locations: classpath*:/mapper/*.xml
server:
port: 8081
前端页面及静态文件信息:
使用的是H+前端模板
页面使用的是Springboot官方推荐thymeleaf
前端资源及本节代码下载:
Shiro简单登录