盐加密
为了数据安全性,我们会使用盐加密
可以将明文转化为密文
我们使用MD5加密
(可以反向解密,解密的原因在于一个明文对应一个密文)
盐加密工具类,在做新增用户的时候使用,将加密后的密码、及加密时候的盐放入数据库;
本篇博客中的表数据是现成的,暂时用不上这个工具类去生成数据;
导入pom.xml依赖
<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>
加盐后一个明文可以对应不同的密文,加了多少次,就可以解密多少次
package com.hsl.ssm.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);//输出结果
}
}
但是当我再一次启动后盐和密文又会不一样
shiro认证
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>
逆向生成对应的表的mapper,model文件
generatorConfig.xml
<table schema="" tableName="t_shiro_permission" domainObjectName="ShiroPermission"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_shiro_role" domainObjectName="ShiroRole"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_shiro_role_permission" domainObjectName="RolePermission"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_shiro_user" domainObjectName="ShiroUser"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_shiro_user_role" domainObjectName="UserRole"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
ShiroUserMapper.java添加
ShiroUser queryByName(@Param("userName") String userName);
ShiroUserMapper.xml添加
<select id="queryByName" resultType="com.hsl.ssm.model.ShiroUser" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from t_shiro_user
where userName = #{userName}
</select>
创建接口ShiroUserService.java
package com.hsl.ssm.service;
import com.hsl.ssm.model.ShiroUser;
/**
* @author water
* @site www.water.com
* @company xxx公司
* @create 2019-12-01 14:38
*/
public interface ShiroUserService {
ShiroUser queryByName( String userName);
}
实现类ShiroUserServiceImpl .java
package com.hsl.ssm.service.impl;
import com.hsl.ssm.mapper.ShiroUserMapper;
import com.hsl.ssm.model.ShiroUser;
import com.hsl.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author water
* @site www.water.com
* @company xxx公司
* @create 2019-12-01 14:39
*/
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper;
@Override
public ShiroUser queryByName(String userName) {
return shiroUserMapper.queryByName(userName);
}
}
创建MyRealm.java
package com.hsl.ssm.shiro;
import com.hsl.ssm.model.ShiroUser;
import com.hsl.ssm.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 water
* @site www.water.com
* @company xxx公司
* @create 2019-11-30 22:01
*
* 充当ini文件
*/
public class MyRealm extends AuthorizingRealm {
private ShiroUserService shiroUserService;
public ShiroUserService getShiroUserService() {
return shiroUserService;
}
public void setShiroUserService(ShiroUserService shiroUserService) {
this.shiroUserService = shiroUserService;
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
* authenticationToken是从controller层传递过来,也就是一些登录操作,会访问这个方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String userName=authenticationToken.getPrincipal().toString();//得到用户名
ShiroUser shiroUser = this.shiroUserService.queryByName(userName);//得到整个用户信息
AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
);
return authenticationInfo;
}
}
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.hsl.ssm.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>
applicationContext.xml添加
<!--整合shiro-->
<import resource="applicationContext-shiro.xml"></import>
controller层
UserController.java
package com.hsl.ssm.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author water
* @site www.water.com
* @company xxx公司
* @create 2019-12-01 15:08
*/
@Controller
public class UserController {
@RequestMapping("/login")
public String login(HttpServletRequest request){
String uname=request.getParameter("username");
String upwd=request.getParameter("password");
UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(uname,upwd);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(usernamePasswordToken);
request.getSession().setAttribute("username",uname);
return "main";
}catch (Exception e){
request.setAttribute("message","用户名或密码错误!!!");
return "login";
}
}
@RequestMapping("/logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login.jsp";
}
}
测试