shiro认证+盐加密
Shiro认证
导入pom依赖
<shiro.version>1.2.5</shiro.version>
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency> <dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency> <dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</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类

这里就不一一展示生成的结果了。
主要看一下需要用到的ShiroUserMapper和ShiroUserMapper.xml
ShiroUserMapper
package com.yuan.mapper; import com.yuan.model.ShiroUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository; @Repository
public interface ShiroUserMapper {
int deleteByPrimaryKey(Integer userid); int insert(ShiroUser record); int insertSelective(ShiroUser record); ShiroUser selectByPrimaryKey(Integer userid); int updateByPrimaryKeySelective(ShiroUser record); int updateByPrimaryKey(ShiroUser record); ShiroUser queryByName(@Param("uname")String uname); }
ShiroUserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yuan.mapper.ShiroUserMapper" >
<resultMap id="BaseResultMap" type="com.yuan.model.ShiroUser" >
<constructor >
<idArg column="userid" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="PASSWORD" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="salt" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="createdate" jdbcType="TIMESTAMP" javaType="java.util.Date" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
userid, username, PASSWORD, salt, createdate
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_shiro_user
where userid = #{userid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_shiro_user
where userid = #{userid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.yuan.model.ShiroUser" >
insert into t_shiro_user (userid, username, PASSWORD,
salt, createdate)
values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{salt,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.yuan.model.ShiroUser" >
insert into t_shiro_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userid != null" >
userid,
</if>
<if test="username != null" >
username,
</if>
<if test="password != null" >
PASSWORD,
</if>
<if test="salt != null" >
salt,
</if>
<if test="createdate != null" >
createdate,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userid != null" >
#{userid,jdbcType=INTEGER},
</if>
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="salt != null" >
#{salt,jdbcType=VARCHAR},
</if>
<if test="createdate != null" >
#{createdate,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.yuan.model.ShiroUser" >
update t_shiro_user
<set >
<if test="username != null" >
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
PASSWORD = #{password,jdbcType=VARCHAR},
</if>
<if test="salt != null" >
salt = #{salt,jdbcType=VARCHAR},
</if>
<if test="createdate != null" >
createdate = #{createdate,jdbcType=TIMESTAMP},
</if>
</set>
where userid = #{userid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.yuan.model.ShiroUser" >
update t_shiro_user
set username = #{username,jdbcType=VARCHAR},
PASSWORD = #{password,jdbcType=VARCHAR},
salt = #{salt,jdbcType=VARCHAR},
createdate = #{createdate,jdbcType=TIMESTAMP}
where userid = #{userid,jdbcType=INTEGER}
</update> <select id="queryByName" resultType="com.yuan.model.ShiroUser" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from t_shiro_user
where username = #{uname}
</select> </mapper>
Service层
package com.yuan.service; import com.yuan.model.ShiroUser;
import org.apache.ibatis.annotations.Param; public interface ShiroUserService { ShiroUser queryByName(@Param("uname")String uname); int insert(ShiroUser record); }
Service实现类
package com.yuan.service.impl; import com.yuan.mapper.ShiroUserMapper;
import com.yuan.model.ShiroUser;
import com.yuan.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper; @Override
public ShiroUser queryByName(String uname) {
return shiroUserMapper.queryByName(uname);
} @Override
public int insert(ShiroUser record) {
return shiroUserMapper.insert(record);
}
}
MyRealm
package com.yuan.shiro; import com.yuan.mapper.ShiroUserMapper;
import com.yuan.model.ShiroUser;
import com.yuan.service.ShiroUserService;
import lombok.ToString;
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;
import org.springframework.stereotype.Component; /*
替换掉.ini的文件,所有用户的身份数据源
*/
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 principalCollection) {
return null;
} /*
身份认证的方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String uname = authenticationToken.getPrincipal().toString();
String pwd = authenticationToken.getCredentials().toString();
ShiroUser shiroUser = shiroUserService.queryByName(uname); AuthenticationInfo info = new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
); 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.yuan.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.yuan.controller; import com.yuan.model.ShiroUser;
import com.yuan.service.ShiroUserService;
import com.yuan.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
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; @Controller
public class ShiroUserController { @Autowired
private ShiroUserService shiroUserService; /*
用户登录
*/
@RequestMapping("/login")
public String login(HttpServletRequest req){
Subject subject = SecurityUtils.getSubject();
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd); try {
// 这里会跳转到MyRealm中的认证方法
subject.login(token);
req.getSession().setAttribute("username", uname);
return "main"; } catch (AuthenticationException e) {
req.setAttribute("message","用户名或密码错误!!!");
return "login";
} } /*
退出登录
*/
@RequestMapping("/logout")
public String logout(HttpServletRequest req) {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login.jsp";
} /*
用户注册
*/
@RequestMapping("/register")
public String register(HttpServletRequest req, HttpServletResponse resp){
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
String salt = PasswordHelper.createSalt();
String credentials = PasswordHelper.createCredentials(pwd, salt); ShiroUser shiroUser=new ShiroUser();
shiroUser.setUsername(uname);
shiroUser.setPassword(credentials);
shiroUser.setSalt(salt);
int insert = shiroUserService.insert(shiroUser);
if(insert>0){
req.setAttribute("message","注册成功");
return "login";
}
else{
req.setAttribute("message","注册失败");
return "register";
}
} }
盐加密的工具类
PasswordHelper
package com.yuan.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);
}
}
Jsp页面
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="重置">
</form>
</body>
</html>
register.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}/register" method="post">
帐号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="注册">
<input type="button" οnclick="location.href='${pageContext.request.contextPath}/login.jsp'" value="返回">
</form>
</body>
</html>
main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="r" uri="http://shiro.apache.org/tags" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>主界面<%=System.currentTimeMillis()%>,欢迎您:[${sessionScope.username}]</h1>
<ul>
系统功能列表
<li>
<a href="admin/addUser.jsp">用户新增</a>
</li>
<li>
<a href="admin/listUser.jsp">用户查询</a>
</li>
<li>
<a href="admin/resetPwd.jsp">重置用户密码</a>
</li>
<li>
<a href="admin/updateUser.jsp">用户修改</a>
</li>
<li>
<a href="user/updatePwd.jsp">个人密码修改</a>
</li>
<li>
<a href="user/teacher.jsp">老师简介</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/logout">退出系统</a>
</li>
</ul>
<ul>
shiro标签
<li>
<r:hasPermission name="user:create">
<a href="admin/addUser.jsp">用户新增</a>
</r:hasPermission>
</li>
<li>
<a href="admin/listUser.jsp">用户查询</a>
</li>
<li>
<a href="admin/resetPwd.jsp">重置用户密码</a>
</li>
<li>
<r:hasPermission name="user:update">
<a href="admin/updateUser.jsp">用户修改</a>
</r:hasPermission>
</li>
<li>
<a href="user/updatePwd.jsp">个人密码修改</a>
</li>
<li>
<a href="${pageContext.request.contextPath}/logout">退出系统</a>
</li>
</ul>
</body>
</html>
运行结果


谢谢观看!!!
shiro认证+盐加密的更多相关文章
- Shiro加盐加密
接本人的上篇文章<Shiro认证.角色.权限>,这篇文章我们来学习shiro的加盐加密实现 自定义Realm: package com.czhappy.realm; import org. ...
- Shiro身份认证、盐加密
目的: Shiro认证 盐加密工具类 Shiro认证 1.导入pom依赖 <dependency> <groupId>org.apache.shiro</groupId& ...
- 【shiro】(4)---Shiro认证、授权案例讲解
Shiro认证.授权案例讲解 一.认证 1. 认证流程 2.用户密码已经加密.加盐的用户认证 (1)测试类 // 用户登陆和退出,这里我自定了一个realm(开发肯定需要自定义realm获取 ...
- shiro认证-SSM
shiro认证-SSM pom <dependency> <groupId>org.apache.shiro</groupId> <artifactId> ...
- 无状态shiro认证组件(禁用默认session)
准备内容 简单的shiro无状态认证 无状态认证拦截器 import com.hjzgg.stateless.shiroSimpleWeb.Constants; import com.hjzgg.st ...
- 转:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法、shiro认证与shiro授权
原文地址:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法.shiro认证与shiro授权 以下是部分内容,具体见原文. shiro介绍 什么是shiro shiro是Apache ...
- Shrio00 Shiro认证登录、权限管理环境搭建
基础环境准备: JDK -> java version "1.8.0_101" MAVEN -> Apache Maven 3.5.0 1 导入依赖 mysql驱动 m ...
- Apach Shiro MD5密码加密过程(明文生成密码过程)详细解析
前言: 最近再项目当中使用的ApachShiro安全框架,对于权限和服务器资源的保护都有一个很好的管理.前期主要参考的文章有 项目中设计密码的加盐处理以及二次加密问题,跟着断点 一步步揭开Apach ...
- Shiro认证、角色、权限
Apache Shiro 是 Java 的一个安全框架.Shiro 可以帮助我们完成:认证.授权.加密.会话管理.与 Web 集成.缓存等. Shiro的内置Realm:IniRealm和JdbcRe ...
随机推荐
- 1.JVM前奏篇(看官网怎么说)
JVM(Java Virtual Machine) 前奏篇(看官网规范怎么说) 1.The relation of JDK/JRE/JVM 在下图中,我们所接触的,最熟悉,也是经常打交道的 最顶层 J ...
- gorm 处理时间戳
问题 在使用 gorm 的过程中, 处理时间戳字段时遇到问题.写时间戳到数据库时无法写入. 通过查阅资料最终问题得以解决,特此总结 设置数据库的 dsn parseTime = "True& ...
- BBR 安装
谷歌云申请搭建翻墙 1.申请谷歌账号 2.申请免费一年谷歌云使用 https://console.cloud.google.com/ 3.设置客户端 xshell/ putty ssh客户端设置 vi ...
- (转)Nginx+rtmp+ffmpeg搭建流媒体服务器
(1)下载第三方扩展模块nginx-rtmp-module # mkdir module && cd module //创建一个存放模块的目录 # wget https://githu ...
- [POJ3682]King Arthur's Birthday Celebration[期望DP]
也许更好的阅读体验 \(\mathcal{Description}\) 每天抛一个硬币,硬币正面朝上的几率是p,直到抛出k次正面为止结束,第\(i\)天抛硬币的花费为\(2i-1\),求出抛硬币的天数 ...
- golang ---获取IP Address
package main import ( "fmt" "log" "os/exec" "regexp" ) func ...
- JAVA MyBybatis分页
java: import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; impo ...
- python3--说简单也不简单的排序算法
在刚开始接触算法时,我们可能一脸懵,不知从何处下手,尤其是现在使用的语言五花八门,各种语言的实现又不尽相同,所以,在这种情况下,千万不能迷失了自己,掌握了算法的原理,就像解数学公式一样,定理给你了,仔 ...
- python 直角图标生成圆角图标
参考链接:https://stackoverflow.com/questions/11287402/how-to-round-corner-a-logo-without-white-backgroun ...
- VS2017 配置 boost_1_70
1. 下载与安装 1.1 安装方法1 (1) 下载 https://www.boost.org/ 或者使用 https://sourceforge.net/projects/boost/files/b ...