Shiro02
Shiro认证
Pom依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.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>
web.xml配置
<!-- shiro过滤器定义 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
通过逆向工程将五张表生成对应的model、mapper
Mapper中新增
<select id="queryByName" resultType="com.liuwenwu.model.ShiroUser" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from t_shiro_user
where username =#{uname}
</select>
ShiroUserService
package com.liuwenwu.service; import com.liuwenwu.model.ShiroUser; /**
* @author LWW
* @site www.lww.com
* @company
* @create 2019-10-13 16:11
*/
public interface ShiroUserService {
/**
* 用于shiro认证
* @param uname
* @return
*/
public ShiroUser queryByName(String uname); /**
* 新增用户
* @param record
* @return
*/
public int insert(ShiroUser record); }
ShiroUserServiceImpl
package com.liuwenwu.service.impl; import com.liuwenwu.mapper.ShiroUserMapper;
import com.liuwenwu.model.ShiroUser;
import com.liuwenwu.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @author LWW
* @site www.lww.com
* @company
* @create 2019-10-13 16:14
*/
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper; @Override
public ShiroUser queryByName(String uname) { return shiroUserMapper.queryByName(uname);
} /**
* 新增用户
* @param record
* @return
*/
@Override
public int insert(ShiroUser record) {
return shiroUserMapper.insert(record);
}
}
MyRealm.java
package com.liuwenwu.shiro; import com.liuwenwu.model.ShiroUser;
import com.liuwenwu.service.ShiroUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource; /**
* @author LWW
* @site www.lww.com
* @company
* @create 2019-10-13 16:02
*
* 认证的过程
* 1、数据源 (ini->>数据库)
* 2、doGetAuthenticationInfo将数据库的用户信息给subject主体做shiro认证的
* 2.1、需要在当前的realm中调用service来验证,当前用户是否在数据库中存在
* 2.2、盐加密
* */
public class MyRealm extends AuthorizingRealm {
private ShiroUserService shiroUserService; public ShiroUserService getShiroUserService() {
return shiroUserService;
} public void setShiroUserService(ShiroUserService shiroUserService) {
this.shiroUserService = shiroUserService;
} @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
} /**
* 认证
* @param token 从jsp传递过来的用户名,密码组合成的一个token对象
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// jsp获取用户名,密码
String userName = token.getPrincipal().toString();
String pwd = token.getCredentials().toString();
// 比对
ShiroUser shiroUser = this.shiroUserService.queryByName(userName);
// 认证
AuthenticationInfo info= new SimpleAuthenticationInfo(
shiroUser.getUsername(),//用户名
shiroUser.getPassword(),//密码
ByteSource.Util.bytes(shiroUser.getSalt()),//盐
this.getName()//当前realm的名字
);
return info;
}
}
applicationContext-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--配置自定义的Realm-->
<bean id="shiroRealm" class="com.liuwenwu.shiro.MyRealm">
<property name="shiroUserService" ref="shiroUserService" />
<!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
<!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
<!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
<!--以下三个配置告诉shiro将如何对用户传来的明文密码进行加密-->
<property name="credentialsMatcher">
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!--指定hash算法为MD5-->
<property name="hashAlgorithmName" value="md5"/>
<!--指定散列次数为1024次-->
<property name="hashIterations" value="1024"/>
<!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储-->
<property name="storedCredentialsHexEncoded" value="true"/>
</bean>
</property>
</bean> <!--注册安全管理器-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="shiroRealm" />
</bean> <!--Shiro核心过滤器-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 身份验证失败,跳转到登录页面 -->
<property name="loginUrl" value="/login"/>
<!-- 身份验证成功,跳转到指定页面 -->
<!--<property name="successUrl" value="/index.jsp"/>-->
<!-- 权限验证失败,跳转到指定页面 -->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
<!--
注:anon,authcBasic,auchc,user是认证过滤器
perms,roles,ssl,rest,port是授权过滤器
-->
<!--anon 表示匿名访问,不需要认证以及授权-->
<!--authc表示需要认证 没有进行身份认证是不能进行访问的-->
<!--roles[admin]表示角色认证,必须是拥有admin角色的用户才行-->
/user/login=anon
/user/updatePwd.jsp=authc
/admin/*.jsp=roles[admin]
/user/teacher.jsp=perms["user:update"]
<!-- /css/** = anon
/images/** = anon
/js/** = anon
/ = anon
/user/logout = logout
/user/** = anon
/userInfo/** = authc
/dict/** = authc
/console/** = roles[admin]
/** = anon-->
</value>
</property>
</bean> <!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
ShiroUserController
package com.liuwenwu.controller; import com.liuwenwu.model.ShiroUser;
import com.liuwenwu.service.ShiroUserService;
import com.liuwenwu.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* @author LWW
* @site www.lww.com
* @company
* @create 2019-10-13 16:52
*/
@Controller
public class ShiroUserController { @Autowired
private ShiroUserService shiroUserService; /**
* 登录
* @param req
* @param resp
* @return
*/
@RequestMapping("/login")
public String login(HttpServletRequest req, HttpServletResponse resp){
Subject subject = SecurityUtils.getSubject();//拿到登录主体
// 拿到jsp传递过来的用户名,密码
String uname =req.getParameter("username");
String pwd = req.getParameter("password");
// 生成令牌
UsernamePasswordToken token =new UsernamePasswordToken(uname,pwd);
try {
subject.login(token);//登录
return "main";
}catch (Exception e){
req.setAttribute("message","用户名或密码错误");//错误信息
return "login";
} } /**
* 登出
* @param req
* @param resp
* @return
*/
@RequestMapping("/logout")
public String logout(HttpServletRequest req, HttpServletResponse resp){
Subject subject = SecurityUtils.getSubject();//拿到登录主体
subject.logout();
return "login";
} /**
* 新增用户
* @param shiroUser
* @param req
* @param resp
* @return
*/
@RequestMapping("/add")
public String add(ShiroUser shiroUser, HttpServletRequest req, HttpServletResponse resp){
// 获取前台出过来的用户名和密码
String uname =req.getParameter("username1");
String pwd = req.getParameter("password1");
shiroUser.setUsername(uname);
// 使用工具类生成盐
String salt = PasswordHelper.createSalt();
shiroUser.setSalt(salt);
// 盐加密后得到的密码
String credentials = PasswordHelper.createCredentials(pwd, salt);
shiroUser.setPassword(credentials);
// 新增
int aa =this.shiroUserService.insert(shiroUser);
if(aa>0){
req.setAttribute("message","成功");
return "login";
}
else{
req.setAttribute("message","失败");
return "login";
} }
}
PasswordHelper工具类
package com.liuwenwu.util; import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash; public class PasswordHelper { /**
* 随机数生成器
*/
private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator(); /**
* 指定hash算法为MD5
*/
private static final String hashAlgorithmName = "md5"; /**
* 指定散列次数为1024次,即加密1024次
*/
private static final int hashIterations = 1024; /**
* true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储
*/
private static final boolean storedCredentialsHexEncoded = true; /**
* 获得加密用的盐
*
* @return
*/
public static String createSalt() {
return randomNumberGenerator.nextBytes().toHex();
} /**
* 获得加密后的凭证
*
* @param credentials 凭证(即密码)
* @param salt 盐
* @return
*/
public static String createCredentials(String credentials, String salt) {
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials,
salt, hashIterations);
return storedCredentialsHexEncoded ? simpleHash.toHex() : simpleHash.toBase64();
} /**
* 进行密码验证
*
* @param credentials 未加密的密码
* @param salt 盐
* @param encryptCredentials 加密后的密码
* @return
*/
public static boolean checkCredentials(String credentials, String salt, String encryptCredentials) {
return encryptCredentials.equals(createCredentials(credentials, salt));
} public static void main(String[] args) {
//盐
String salt = createSalt();
System.out.println(salt);
System.out.println(salt.length());
//凭证+盐加密后得到的密码
String credentials = createCredentials("123", salt);
System.out.println(credentials);
System.out.println(credentials.length());
boolean b = checkCredentials("123", salt, credentials);
System.out.println(b);
}
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>用户登陆</h1>
<div style="color: red">${message}</div>
<form action="${pageContext.request.contextPath}/login" method="post">
帐号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="确定">
<input type="reset" value="重置">
<input type="button" onclick="window.location='add.jsp'" value="注册">
</form>
</body>
</html>
add.jsp
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2019/10/13
Time: 18:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div style="color: red">${message}</div>
<form action="${pageContext.request.contextPath}/add" method="post">
帐号:<input type="text" name="username1"><br>
密码:<input type="password" name="password1"><br>
<input type="submit" value="确定">
<input type="reset" value="重置">
</form>
</body>
</html>
登录认证
新增效果:每个新增用户的密码都是123,但生成的加密密码 和盐都是不一样的
Shiro02的更多相关文章
- Java-Shiro(二):HelloWord
新建项目&&配置pom.xml导入包 新建maven java project项目: 修改pom.xml: <project xmlns="http://maven.a ...
- 【Shiro】Apache Shiro架构之身份认证(Authentication)
Shiro系列文章: [Shiro]Apache Shiro架构之权限认证(Authorization) [Shiro]Apache Shiro架构之集成web [Shiro]Apache Shiro ...
- ShiroUtil 对密码进行加密
ShiroUtil 对密码进行加密 package com.mozq.sb.shiro02.config; import org.apache.shiro.authc.SimpleAuthentica ...
随机推荐
- 解决:CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
log4j给出的异常信息有下面几句: Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC C ...
- 解决iOS上网页滑动不流畅问题
body { overflow:auto; /* 用于 android4+,或其他设备 */ -webkit-overflow-scrolling:touch; /* 用于 ios5+ */ }说明: ...
- 01_安装电脑软件的步骤批处理脚本.bat
REM 01_安装电脑软件的步骤批处理脚本.bat MD 01_安装电脑软件的步骤 REM ZIP解压密码空格MD 02_制作杏雨梨云USB维护系统2019中秋版之国庆更新固态U盘MD 03_复制安装 ...
- mitmproxy第一次尝试-猿人学第九题
启动 mitmdump -s http_proxy.py -p 9000 替换js代码 # -*- coding: utf-8 -*- import re main_url = 'http://mat ...
- 网络编程之TCP客户端开发和TCP服务端开发
开发 TCP 客户端程序开发步骤 创建客户端套接字对象 和服务端套接字建立连接 发送数据 接收数据 关闭客户端套接字 import socket if __name__ == '__main__': ...
- 2021字节跳动校招秋招算法面试真题解题报告--leetcode206 反转链表,内含7种语言答案
206.反转链表 1.题目描述 反转一个单链表. 示例: 输入: 1->2->3->4->5->NULL输出: 5->4->3->2->1-> ...
- 获取异常信息里再出异常就找不到日志了,我TM人傻了
本系列是 我TM人傻了 系列第三期[捂脸],往期精彩回顾: 升级到Spring 5.3.x之后,GC次数急剧增加,我TM人傻了 这个大表走索引字段查询的 SQL 怎么就成全扫描了,我TM人傻了 最近组 ...
- 工资8000以下的Android程序员注意了!接下来要准备面对残酷现实了……
最近在知乎看到一个测试,特扎心: 以下三种情况,哪个最让你绝望? ❶ 每月工资去掉开销还存不到3千: ❷ 家人突然急病住院,医药费10万: ❸ 同班的家长都在争先恐后给孩子报名各种辅导班.兴趣班,但一 ...
- 绿色djvu阅读软件
官方的djvu viewer都需要安装,总算找到一个绿色版的,名为STDU Viewer,可以阅读的格式包括DjVu, PDF, TIFF, XPS, FB2等,版本为1.6.2.
- JavaScript学习05(操作DOM)
操作DOM DOM(文档对象模型) 当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model). HTML DOM 模型被结构化为对象树: 通过这个对象模型,Java ...