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 ...
随机推荐
- mysql5.5免安装版配置教程
1. 下载免安装版 ,解压缩 2. 配置MYSQL的环境变量 新增系统变量MYSQL_HOME:安装目录 在PATH变量的最后面添加: ;%MYSQL_HOME%\bin(注意前面的:) 3. 打开文 ...
- 15 IO流(十二)——数据流Data InputStream/OutputStream 未学会
数据流的引入 Data流的父类是Filter抽象基类,也就是说Data流是装饰流. 数据流可以将数据的类型也一起传输. 数据流的读取写入顺序(数据类型的读写顺序)需要一致. 未完成代码 /** *Da ...
- Altium Designer 复制报错-奇怪的问题解决办法
之前AD画原理图复制元件正常使用,今天使用时复制弹出了错误.很是诧异! 各种搜索查找问题,发现或许是因为前一段时间把,电脑上的所有打印机都删除了导致的. 就安装了一个打印机. 再复制,就不报错了. 或 ...
- asp.net Code CSRedis学习记录
1.安装Redis for windows 安装地址 https://github.com/MicrosoftArchive/redis/releases Redis 是完全开源免费的,遵守BSD协议 ...
- 在springMVC的controller中获取request,response对象的一个方法
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttr ...
- mysql 字符
只适用mysql5.0以上的版本: 1.一个汉字占多少长度与编码有关: UTF-8:一个汉字=3个字节 GBK:一个汉字=2个字节 2.varchar(n)表示n ...
- Python Django 协程报错,进程池、线程池与异步调用、回调机制
一.问题描述 在Django视图函数中,导入 gevent 模块 import gevent from gevent import monkey; monkey.patch_all() from ge ...
- php后台实现页面跳转的方法-转载
地址:http://blog.csdn.net/abandonship/article/details/6459104 其中方法三的js代码在tp框架使用存在故障,一个是需要把代码写在一起(可能也不需 ...
- Centos 端口被占用,kill被占用的进程
1.yum install lsof 2.输入netstat -tln,查看系统当前所有被占用端口 3.根据端口查询进程,输入lsof -i :9555,切记不要忘了添加冒号 4. 既然知道进程号了, ...
- Kubernetes 1.15部署日记-使用kubeadm--<7-8>
7. 在k8s集群中run一个应用 nginx已经跑起来了到此kubernetes集群部署结束了. 8. 总结 此次部署kubernetes的起因是AI团队中的kubernetes项目跑在其他IP段网 ...