shiro mysql_Shiro系列之Shiro+Mysql实现用户认证(Authentication)
网上大多数介绍Apache Shiro的资料都是使用ini文件的简单配置为例,很少用讲到如何配合数据库来实现用户认证的。我也是刚刚开始接触Shiro,在这里介绍一个入门级别的Shiro+Mysql的配置方法,这个方法仅仅是个开始,并没有和Web,Spring,Mybatis等框架进行整合,后续我还会继续和大家分享我的学习过程及心得。
now we can start the things that we really care about.
数据库中创建一个用户表,字段可以很简单。
CREATE TABLE `sec_user` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`password` varchar(128) COLLATE utf8_bin DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
在表中插入一条记录,用户名:chris.mao.zb@163.com,密码:cmao
在resources目录下创建一个ini文件,配置Shiro(后续文件会将此文件内容移至XML文件中)。在这个配置文件中我们要设置数据源,以及用户认证时使用数据库查询语句。这里用到了Shiro中自带的JdbcRealm类。
[main]
dataSource=org.springframework.jdbc.datasource.DriverManagerDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://127.0.0.1:3306/YOUR_DATABASE_NAME
dataSource.username=YOUR_USERNAME
dataSource.password=YOUR_PASSWORD
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.dataSource=$dataSource
jdbcRealm.authenticationQuery = SELECT password FROM sec_user WHERE user_name = ?
securityManager.realms=$jdbcRealm
关于用户认证的查询语句,我在这里多说两句,小伙伴们不要嫌我啰嗦。我们只需要以用户名为查询条件,查询出密码字段即可,如果您在select后面使用了星号(*)或是查询字段多于一个,都无法通过用户认证 。
配置文件写好后,我们就可以动手写个测试方法,来验证是否可以实现用户认证功能了。
package com.emerons.learning;
import static org.junit.Assert.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
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.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JdbcRealmTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
// 1.获取SecurityManager工厂,此处使用ini配置文件初始化SecurityManager
Factory factory = new IniSecurityManagerFactory("classpath:shiro-jdbc-realm.ini");
// 2.获取SecurityManager实例,并绑定到SecurityUtils
SecurityManager sm = factory.getInstance();
SecurityUtils.setSecurityManager(sm);
// 3.得到Subject
Subject subject = SecurityUtils.getSubject();
// 4.创建用户登录凭证
UsernamePasswordToken token = new UsernamePasswordToken("chris.mao@emerson.com", "chrismao");
// 5.登录,如果登录失败会抛出不同的异常,根据异常输出失败原因
try {
subject.login(token);
// 6.判断是否成功登录
assertEquals(true, subject.isAuthenticated());
System.out.println("登录成功!!");
// 7.注销用户
subject.logout();
} catch (IncorrectCredentialsException e) {
System.out.println("登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.");
} catch (ExcessiveAttemptsException e) {
System.out.println("登录失败次数过多");
} catch (LockedAccountException e) {
System.out.println("帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.");
} catch (DisabledAccountException e) {
System.out.println("帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.");
} catch (ExpiredCredentialsException e) {
System.out.println("帐号已过期. the account for username " + token.getPrincipal() + " was expired.");
} catch (UnknownAccountException e) {
System.out.println("帐号不存在. There is no user with username of " + token.getPrincipal());
}
}
}
运行测试代码,得到如下输出:
INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
INFO : org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set. Authorization cache cannot be obtained.
INFO : org.apache.shiro.config.IniSecurityManagerFactory - Realms have been explicitly set on the SecurityManager instance - auto-setting of realms will not occur.
INFO : org.apache.shiro.session.mgt.AbstractValidatingSessionManager - Enabling session validation scheduler...
登录成功!!
INFO : org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set. Authorization cache cannot be obtained.
我们从日志上可以看到,程序加载了Jdbc驱动,明确指定了realm,这说明我们的Shiro配置文件加载成功。最后看到输出了“登录成功”说明这个认证功能已经实现了。大家也可以试着修改测试代码用的用户名或是密码,可以在控制台看到类似下面的输出,说明也可以抛出正确的异常。
INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
INFO : org.apache.shiro.realm.AuthorizingRealm - No cache or cacheManager properties have been set. Authorization cache cannot be obtained.
INFO : org.apache.shiro.config.IniSecurityManagerFactory - Realms have been explicitly set on the SecurityManager instance - auto-setting of realms will not occur.
登录密码错误. Password for account chris.mao@emerson.com was incorrect.
至此,使用Shiro + Mysql实现用户认证(Authentication)的功能已经完成。大家可以在这个基础上,完善实现角色授权(Authroization),操作允可(Permission)等功能,参见《Shiro系列之Shiro+Mysql实现用户授权(Authorization)》
shiro mysql_Shiro系列之Shiro+Mysql实现用户认证(Authentication)相关推荐
- mysql邮箱认证_邮件服务系列postfix+sasl+mysql实现用户认证功能
1.卸载bind [root@mail ~]# rpm -e bind-utils 2.安装bind97-utils bind97-libs bind97 [root@mail ~]# yum ins ...
- shiro学习系列:shiro自定义filter过滤器
shiro学习系列:shiro自定义filter过滤器 自定义JwtFilter的hierarchy(层次体系) 上代码 package com.finn.springboot.common.conf ...
- linux ftp 团队认证,linux下ftp和ftps以及ftp基于mysql虚拟用户认证服务器的搭建
linux下ftp和ftps以及ftp基于mysql虚拟用户认证服务器的搭建 1.FTP协议:有命令和数据连接两种 命令连接,控制连接:21/tcp 数据连接: 主动模式,运行在20/tcp端口 和 ...
- linux ftp mysql_linux下ftp和ftps以及ftp基于mysql虚拟用户认证服务器的搭建
命令连接,控制连接:21/tcp 数据连接: 主动模式,运行在20/tcp端口 和 被动模式,运行在随机端口 数据传输模式(自动模式):有二进制(mp3,jpg等)和文本(html)两种传输模式 ft ...
- MySQL普通用户无法本地登录的解决方法及MySQL的用户认证算法
在安装完成MySQL后,我们通常添加拥有相应权限的普通用户用来访问数据库.在使用普通用户本地登录数据库的时候,经常会出现怎么登录也无法登录的情况. 例如,我的MySQL中的用户为: mysql> ...
- python 用户认证_python基于mysql的用户认证
首先,创建mysql用户users表 1 2 3 4 5 create table users ( id int NOT NULL primary key auto_increment, userna ...
- Spring Boot整合Shiro + JSP教程(用户认证,权限管理,图片验证码)
在此首先感谢**编程不良人**up主提供的视频教程 代码都是跟着up的视频敲的,遇到的一些问题也是通过CSDN博主提供的教程解决的,在此也感谢那些提供bug解决方案的前辈们~ 项目完整代码已经发布到g ...
- mysql 查询用户最后登陆时间_弄懂mysql:mysql的通信协议
我准备从mysql的实现出发,将mysql好好理解一下,从他的逻辑结构一层一层出发,感受一下,所以再学第一层之前,要先对mysql整体的逻辑结构有一个初步认识 mysql逻辑架构 整体来说,MySql ...
- Java-SpringBoot:用户认证(Authentication)和用户授权(Authorization)
Java-SpringBoot-2 学习视频:B站 狂神说Java – https://www.bilibili.com/video/BV1PE411i7CV 学习文档: 微信公众号 狂神说 –htt ...
最新文章
- 我们为什么要尝试前后端分离
- C++函数模板(一)
- Lead saved query bug
- 使用run-rs启动mongodb
- VC启动窗口画面制作方法研究
- 计算机安装最新的安全补丁,Win10不要装!微软发布4月安全补丁合集
- 微软开始取消 Windows 10 对 32 位系统的支持
- datagridview数据导出到excel
- mysql group 最大值_MySQL groupwise最大值为字段的长度
- c语言程序设计实验第二版答案,C语言程序设计实验指导及习题答案
- MongoDB可视化工具MongoChef永久有效
- VMware Workstation Server 服务器启动报1075错误
- Android Binder传递文件描述符原理分析
- 用python计算圆柱体积
- AJAX(七)jsonp实战--天气预报
- Prometheus-----1
- 4天接待180万游客!里昂灯光节的这些作品你都看懂了吗?
- file-uploader-cli 关于上传至京东云中文件夹问题的源码修改
- 使用stm32c8t6和mpu6050制作一台穿越机
- 最新CFA二级notes 原版书 课后习题
热门文章
- 锤子新机终于来了?10月31日发布,连海报都做好了?
- 三星Galaxy A10s海报曝光:6.2寸水滴屏+4000mAh电池
- 拼多多董事会变更:董事6人变5人 张震不再出任
- 网红第一股上市首日暴跌37% “为人低调”王思聪评价:公司本身有问题
- 百度总裁张亚勤十月退休:感谢李彦宏和百度 很高兴能安心退休
- 昨天去面试字节软件测试,总结了一些建议分享,附带相关面试题...
- Java成神之路——volatile是什么?
- php pcre回溯攻击,PHP利用PCRE回溯次数限制绕过某些安全限制 | 码农网
- python成绩统计_python统计考试成绩排名
- MFC小笔记:开机自动启动