目录
4.applicationContext-shiro.xml
在面对这个网络世界的时候,密码安全总是各个公司和用户都非常关心的一个内容,毕竟现在大家不管是休闲娱乐还是学习购物都是通过网上的帐号来进行消费的,所以我们通常会给用户的密码进行加密。在加密的时候,经常会听到“加盐”这个词,这是什么意思呢?
我们通常会将用户的密码进行 Hash 加密,如果不加盐,即使是两层的 md5 都有可能通过彩虹表的方式进行破译。彩虹表就是在网上搜集的各种字符组合的 Hash 加密结果。而加盐,就是人为的通过一组随机字符与用户原密码的组合形成一个新的字符,从而增加破译的难度。就像做饭一样,加点盐味道会更好。
数据库密码的发展史
第一个阶段:明文密码
第二个阶段:md5加密
第三个阶段:md5加盐加密
第四个阶段:md5加盐加密加次数由于明文密码泄露出去后很容易会造成不好的影响,没有保密性,所以就有了之后的各种加密方式 本期我们使用的是md5加盐加密加次数的加密方式
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-coreartifactId>
- <version>1.3.2version>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-webartifactId>
- <version>1.3.2version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-springartifactId>
- <version>1.3.2version>
- dependency>
- <filter>
- <filter-name>shiroFilterfilter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
- <init-param>
-
- <param-name>targetFilterLifecycleparam-name>
- <param-value>trueparam-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>shiroFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
导入一个测试类 PasswordHelper
- package com.ljj.shiro;
-
-
- import org.apache.shiro.crypto.RandomNumberGenerator;
- import org.apache.shiro.crypto.SecureRandomNumberGenerator;
- import org.apache.shiro.crypto.hash.SimpleHash;
-
- /**
- * 用于shiro权限认证的密码工具类
- */
- 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("123456", salt);
- System.out.println(credentials);
- System.out.println(credentials.length());
- boolean b = checkCredentials("123456", salt, credentials);
- System.out.println(b);
- }
- }
测试结果:
结果解析:
测试方法中的原密码:123456
随机获得的盐:b837c1697d811401c6ecb857083fa7b8
长度:32
加密后的密码:ba73e39bee3b55f925f57e6c4e3cb577
长度 32
与原密码匹配是否成功:true
上一期我们的数据为定死的死数据,这次我们使用数据库数据
使用前端代码自动生成器
- <table schema="" tableName="t_shiro_permission" domainObjectName="Permission"
- enableCountByExample="false" enableDeleteByExample="false"
- enableSelectByExample="false" enableUpdateByExample="false">
- table>
- <table schema="" tableName="t_shiro_user" domainObjectName="User"
- enableCountByExample="false" enableDeleteByExample="false"
- enableSelectByExample="false" enableUpdateByExample="false">
- table>
- <table schema="" tableName="t_shiro_role" domainObjectName="Role"
- 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>
- <table schema="" tableName="t_shiro_role_permission" domainObjectName="RolePermission"
- enableCountByExample="false" enableDeleteByExample="false"
- enableSelectByExample="false" enableUpdateByExample="false">
- table>
生成成功
在UserMapper.xml中编写一个按用户账号查询的方法
- !-- 通过用户名进行查询-->
- <select id="queryUserByserName" resultType="com.ljj.ssm.model.User" parameterType="java.lang.String" >
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where username = #{userName}
- select>
UserMapper.java
User queryUserByserName(@Param("userName") String userName);
Biz层:UserBiz
- package com.ljj.ssm.biz;
-
- import com.ljj.ssm.model.User;
-
- public interface UserBiz {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryUserByserName(String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
- }
UserBizImpl:
- package com.ljj.ssm.biz.impl;
-
- import com.ljj.ssm.biz.UserBiz;
- import com.ljj.ssm.mapper.UserMapper;
- import com.ljj.ssm.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- /**
- * @author ljj
- * @site www.ljj.com
- * @create 2022-08-25 16:54
- */
- @Service("userBiz")
- public class UserBizImpl implements UserBiz {
- @Autowired
- private UserMapper userMapper;
- @Override
- public int deleteByPrimaryKey(Integer userid) {
- return userMapper.deleteByPrimaryKey(userid);
- }
-
- @Override
- public int insert(User record) {
- return userMapper.insert(record);
- }
-
- @Override
- public int insertSelective(User record) {
- return userMapper.insertSelective(record);
- }
-
- @Override
- public User selectByPrimaryKey(Integer userid) {
- return userMapper.selectByPrimaryKey(userid);
- }
-
- @Override
- public User queryUserByserName(String userName) {
- return userMapper.queryUserByserName(userName);
- }
-
- @Override
- public int updateByPrimaryKeySelective(User record) {
- return userMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(User record) {
- return userMapper.updateByPrimaryKey(record);
- }
- }
- package com.ljj.ssm.shiro;
-
- import com.ljj.ssm.biz.UserBiz;
- import com.ljj.ssm.model.User;
- 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 ljj
- * @site www.ljj.com
- * @create 2022-08-25 17:04
- */
- public class MyRealm extends AuthorizingRealm {
-
- public UserBiz userBiz;
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- /**
- * 授权
- * @param principals
- * @return
- * 相当于上一期中shiro_web.ini
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- return null;
- }
-
- /**
- * 认证
- * @param token
- * @return
- * @throws AuthenticationException
- * 相当于上一期中shiro.ini
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- String userName = token.getPrincipal().toString();
- User user = userBiz.queryUserByserName(userName);
- AuthenticationInfo info = new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName() //realm的名字
- );
- return info;
- }
- }
-
3.1 shiro在加载的时候,Spring上下文还没有加载完毕,所以@component与@autowised是不能使用的 所以此次要编写get set方法
3.2 spring-shiro.xml文件中,MyRealm需要依赖的业务类:
由于没有被Spring配置,所以需要指定bean的id 通过@Service("具体的名字")
配置自定义的Realm&指定算法&Shiro核心过滤器
- "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">
-
-
- <bean id="shiroRealm" class="com.ljj.ssm.shiro.MyRealm">
- <property name="userBiz" ref="userBiz" />
-
-
-
-
- <property name="credentialsMatcher">
- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
-
- <property name="hashAlgorithmName" value="md5"/>
-
- <property name="hashIterations" value="1024"/>
-
- <property name="storedCredentialsHexEncoded" value="true"/>
- bean>
- property>
- bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager" />
-
- <property name="loginUrl" value="/login"/>
-
-
-
- <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
-
- <property name="filterChainDefinitions">
- <value>
-
-
-
-
- /user/login=anon
- /user/updatePwd.jsp=authc
- /admin/*.jsp=roles[admin]
- /user/teacher.jsp=perms["user:update"]
-
- value>
- property>
- bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
- beans>
测试成功
结论:DoGetAuthenticationInfo认证方法是web层执行subject.ligin出发的;