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 ...
随机推荐
- shiro反序列化550、721
shiro550反序列化 获取docker镜像 docker pull medicean/vulapps:s_shiro_1 重启docker systemctl restart docker 启动d ...
- 在屏幕上搜索图片并返回图片所在位置的坐标的AutoHotkey脚本源代码(类似大漠插件)
;~ 在屏幕上搜索图片并返回图片所在位置的坐标的AutoHotkey脚本源代码(类似大漠插件) ; https://www.autohotkey.com/boards/viewtopic.php?t ...
- Python - 函数实战
前言 参考的是慕课网提供的实战,自己编码 http://www.imooc.com/wiki/pythonlesson1/function2.html 什么是模块化程序设计 在进行程序设计时将一个大程 ...
- ContentObserver 内容观察者作用及特点
eg: 1.定义Uri public static Uri KEY_BROWSER_URI = Uri.parse("content://com.android.browser.provid ...
- Java数组02——三种初始化及内存分析
内存分析 三种初始化 例子 package array; public class ArrayDemon02 { public static void main(String[] arg ...
- 我把阿里、腾讯、字节跳动、美团等Android性能优化实战整合成了一个PDF文档
安卓开发大军浩浩荡荡,经过近十年的发展,Android技术优化日异月新,如今Android 11.0 已经发布,Android系统性能也已经非常流畅,可以在体验上完全媲美iOS. 但是,到了各大厂商手 ...
- 用Autohotkey让Kitty命令行变得更好用
下面的脚本实现Win+K键激活一个输入框,给出了kitty命令行常用的几种格式,基本可分为两种:连接保存好的模板(session)和完全手工连接,前者用-load加Session名称,后者需要在命令行 ...
- Redis雪崩和Redis穿透
Redis雪崩:查询时Redis没有数据 本来先从Redis里面查某个数据 但是Redis中这个数据刚好被删除了,还没来得及更新 一瞬间很多请求直接进入了Mysql进行查询 而mysql承受不了太大压 ...
- SQL 练习22
查询出只选修两门课程的学生学号和姓名 --方式1: SELECT Student.SId,Sname from Student WHERE SId in ( SELECT sid from sc GR ...
- 《手把手教你》系列技巧篇(二十一)-java+ selenium自动化测试-浏览器窗口的句柄(详细教程)
1.简介 今天本来就要分享和讲解三大延时等待的,但是在写作过程中发了问题,会用到这一个知识点,于是就提前介绍一下,以便后边用到了可以更好的理解和掌握.本文就是要介绍如何获得浏览器窗体的句柄或者叫编号, ...