• Shiro认证--盐加密(SSM)


    目录

    一、认证

    导入pom依赖

     配置web.xml

    数据表编写好后开始逆向生成

    查数据库的地方就是realm 实现自定义realm接口

    创建自定义域 

    编写认证方法

    二、盐加密

    盐加密,数据库密码发展史


    一、认证

    本期内容代码基于Springmvc内容代码上做shiro延伸

    导入pom依赖

     配置web.xml

    1. <filter>
    2. <filter-name>shiroFilterfilter-name>
    3. <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
    4. <init-param>
    5. <param-name>targetFilterLifecycleparam-name>
    6. <param-value>trueparam-value>
    7. init-param>
    8. filter>
    9. <filter-mapping>
    10. <filter-name>shiroFilterfilter-name>
    11. <url-pattern>/*url-pattern>
    12. filter-mapping>

    这次的web.xml配置与上一期博客内容中web.xml配置相比少了一点内容 监听器 (监听器的作用是加载配置文件中的数据源);为什么不需要监听器呢,因为本次内容的数据源从数据库中加载,所以监听器就不需要了。

    接下来我们通过逆向工程将下图五张表收藏对应的model mapper

    数据表编写好后开始逆向生成

     

     选择当前数据表所在的模块后并点击ok⬇⬇

     开始生成    

    接下来编写查询方法:

    查数据库的地方就是realm 实现自定义realm接口

    1. <!--通过用户名进行查询-->
    2. <select id="queryUserByUserName" resultMap="com.xiaokun.ssm.model.User" parameterType="java.lang.String" >
    3. select
    4. <include refid="Base_Column_List" />
    5. from t_shiro_user
    6. where username = #{userName}
    7. </select>

    编写biz层  

    UserBiz

    1. package com.xiaokun.ssm.biz;
    2. import com.xiaokun.ssm.model.User;
    3. import org.apache.ibatis.annotations.Param;
    4. public interface UserBiz {
    5. int deleteByPrimaryKey(Integer userid);
    6. int insert(User record);
    7. int insertSelective(User record);
    8. User selectByPrimaryKey(Integer userid);
    9. User queryUserByUserName(@Param("userName") String userName);
    10. int updateByPrimaryKeySelective(User record);
    11. int updateByPrimaryKey(User record);
    12. }

    UserBizImpl

    1. package com.xiaokun.ssm.biz.impl;
    2. import com.xiaokun.ssm.biz.UserBiz;
    3. import com.xiaokun.ssm.mapper.UserMapper;
    4. import com.xiaokun.ssm.model.User;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. /**
    8. * @author 小坤
    9. * @create 2022-08-25-13:30
    10. */
    11. @Service
    12. public class UserBizImpl implements UserBiz {
    13. @Autowired
    14. private UserMapper userMapper;
    15. @Override
    16. public int deleteByPrimaryKey(Integer userid) {
    17. return userMapper.deleteByPrimaryKey(userid);
    18. }
    19. @Override
    20. public int insert(User record) {
    21. return userMapper.insert(record);
    22. }
    23. @Override
    24. public int insertSelective(User record) {
    25. return userMapper.insertSelective(record);
    26. }
    27. @Override
    28. public User selectByPrimaryKey(Integer userid) {
    29. return userMapper.selectByPrimaryKey(userid);
    30. }
    31. @Override
    32. public User queryUserByUserName(String userName) {
    33. return userMapper.queryUserByUserName(userName);
    34. }
    35. @Override
    36. public int updateByPrimaryKeySelective(User record) {
    37. return userMapper.updateByPrimaryKeySelective(record);
    38. }
    39. @Override
    40. public int updateByPrimaryKey(User record) {
    41. return userMapper.updateByPrimaryKey(record);
    42. }
    43. }

     UserMapper

    1. package com.xiaokun.ssm.mapper;
    2. import com.xiaokun.ssm.model.User;
    3. import org.apache.ibatis.annotations.Param;
    4. import org.springframework.stereotype.Repository;
    5. @Repository
    6. public interface UserMapper {
    7. int deleteByPrimaryKey(Integer userid);
    8. int insert(User record);
    9. int insertSelective(User record);
    10. User selectByPrimaryKey(Integer userid);
    11. User queryUserByUserName(@Param("userName") String userName);
    12. int updateByPrimaryKeySelective(User record);
    13. int updateByPrimaryKey(User record);
    14. }

    创建自定义域 

    1. package com.xiaokun.ssm.shiro;
    2. import com.xiaokun.ssm.biz.UserBiz;
    3. import org.apache.shiro.authc.AuthenticationException;
    4. import org.apache.shiro.authc.AuthenticationInfo;
    5. import org.apache.shiro.authc.AuthenticationToken;
    6. import org.apache.shiro.authz.AuthorizationInfo;
    7. import org.apache.shiro.realm.AuthorizingRealm;
    8. import org.apache.shiro.subject.PrincipalCollection;
    9. /**
    10. * @author 小坤
    11. * @create 2022-08-25-13:37
    12. */
    13. public class MyRealm extend AuthorizingRealm {
    14. public UserBiz userBiz;
    15. public UserBiz getUserBiz() {
    16. return userBiz;
    17. }
    18. public void setUserBiz(UserBiz userBiz) {
    19. this.userBiz = userBiz;
    20. }
    21. /**
    22. * 授权
    23. * @param principals
    24. * @return
    25. * 替代了上一期博客的shiro-web.ini文件
    26. */
    27. @Override
    28. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    29. return null;
    30. }
    31. /**
    32. * 认证
    33. * @param token
    34. * @return
    35. * @throws AuthenticationException
    36. * shiro.ini
    37. */
    38. @Override
    39. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    40. return null;
    41. }
    42. }

     配置文件

     

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="shiroRealm" class="com.xiaokun.ssm.shiro.MyRealm">
    6. <property name="userBiz" ref="userBiz" />
    7. <property name="credentialsMatcher">
    8. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    9. <property name="hashAlgorithmName" value="md5"/>
    10. <property name="hashIterations" value="1024"/>
    11. <property name="storedCredentialsHexEncoded" value="true"/>
    12. bean>
    13. property>
    14. bean>
    15. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    16. <property name="realm" ref="shiroRealm" />
    17. bean>
    18. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    19. <property name="securityManager" ref="securityManager" />
    20. <property name="loginUrl" value="/login"/>
    21. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    22. <property name="filterChainDefinitions">
    23. <value>
    24. /user/login=anon
    25. /user/updatePwd.jsp=authc
    26. /admin/*.jsp=roles[admin]
    27. /user/teacher.jsp=perms["user:update"]
    28. value>
    29. property>
    30. bean>
    31. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    32. beans>

    Spring与shiro的整合(注意❗shiro在加载的时候,Spring上下文海没有加载完毕,所以@component与@autowised是不能使用的;spring-shiro.xml文件中,MyRealm需要依赖的业务类由于没有被spring配置,所以需要指定bean的id,通过@Service("具体的名字"))

     编写认证方法

    1. /**
    2. * 认证
    3. * @param token
    4. * @return
    5. * @throws AuthenticationException
    6. * shiro.ini
    7. */
    8. @Override
    9. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    10. //拿到用户名
    11. String UserName = token.getPrincipal().toString();
    12. //调用查询方法
    13. User user = userBiz.queryUserByUserName(UserName);
    14. AuthenticationInfo info=new SimpleAuthenticationInfo(
    15. user.getUsername(),
    16. user.getPassword(),
    17. ByteSource.Util.bytes(user.getSalt()),
    18. this.getName()
    19. );
    20. return info;
    21. }

    将前端界面导入

    login.jsp

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Titletitle>
    5. head>
    6. <body>
    7. <h1>用户登陆h1>
    8. <div style="color: red">${message}div>
    9. <form action="${pageContext.request.contextPath}/login" method="post">
    10. 帐号:<input type="text" name="username"><br>
    11. 密码:<input type="password" name="password"><br>
    12. <input type="submit" value="确定">
    13. <input type="reset" value="重置">
    14. form>
    15. body>
    16. html>

     LoginController 

    1. package com.xiaokun.ssm.controller;
    2. import org.apache.shiro.SecurityUtils;
    3. import org.apache.shiro.authc.UsernamePasswordToken;
    4. import org.apache.shiro.subject.Subject;
    5. import org.springframework.stereotype.Controller;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpSession;
    9. @Controller
    10. public class LoginController {
    11. @RequestMapping("/login")
    12. public String login(HttpServletRequest req){
    13. try {
    14. String username = req.getParameter("username");
    15. String password = req.getParameter("password");
    16. UsernamePasswordToken token=new UsernamePasswordToken(username,password);
    17. Subject subject = SecurityUtils.getSubject();
    18. subject.login(token);
    19. return "main";
    20. }catch (Exception e){
    21. req.setAttribute("message","账号密码错误");
    22. return "login";
    23. }
    24. }
    25. @RequestMapping("/logout")
    26. public String logout(HttpServletRequest req){
    27. Subject subject = SecurityUtils.getSubject();
    28. subject.logout();
    29. return "login";
    30. }
    31. }

    resultMap:前提做了映射关系的

    resultType:放实体类

    运行一下

     

    debug断点拿到数据库盐密码 

     

     总结:doGetAuthenticationInfo认证方法是web层执行subject.login 方法触发的

    1.Mapper层        ——        通过账户名获取用户信息

    2.将用户信息给MyRealm 认证方法,认证的过程交给安全管理器

    3.MyRealm的配置,配置spring-shiro.xml 文件中

            ① shiro接管MyRealm的时候,还没有被Spring所接管导致@component与        @autowised用不了

            ② 采用配置的形式配置UserBiz,需要给@service指定bean的名称

    二、盐加密

    盐加密,数据库密码发展史

    第一阶段:明文密码(在数据库中展现出来的密码)

    第二阶段:MD5加密

    第三阶段:MD5加盐加密

    第四阶段:MD5加盐加密加次数

    创建一个测试包,演示盐加密

    创建一个类PasswordHelper

    1. package com.xiaokun.shiro;
    2. import org.apache.shiro.crypto.RandomNumberGenerator;
    3. import org.apache.shiro.crypto.SecureRandomNumberGenerator;
    4. import org.apache.shiro.crypto.hash.SimpleHash;
    5. /**
    6. * 用于shiro权限认证的密码工具类
    7. */
    8. public class PasswordHelper {
    9. /**
    10. * 随机数生成器
    11. */
    12. private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    13. /**
    14. * 指定hash算法为MD5
    15. */
    16. private static final String hashAlgorithmName = "md5";
    17. /**
    18. * 指定散列次数为1024次,即加密1024次
    19. */
    20. private static final int hashIterations = 1024;
    21. /**
    22. * true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储
    23. */
    24. private static final boolean storedCredentialsHexEncoded = true;
    25. /**
    26. * 获得加密用的盐
    27. *
    28. * @return
    29. */
    30. public static String createSalt() {
    31. return randomNumberGenerator.nextBytes().toHex();
    32. }
    33. /**
    34. * 获得加密后的凭证
    35. *
    36. * @param credentials 凭证(即密码)
    37. * @param salt 盐
    38. * @return
    39. */
    40. public static String createCredentials(String credentials, String salt) {
    41. SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials,
    42. salt, hashIterations);
    43. return storedCredentialsHexEncoded ? simpleHash.toHex() : simpleHash.toBase64();
    44. }
    45. /**
    46. * 进行密码验证
    47. *
    48. * @param credentials 未加密的密码
    49. * @param salt 盐
    50. * @param encryptCredentials 加密后的密码
    51. * @return
    52. */
    53. public static boolean checkCredentials(String credentials, String salt, String encryptCredentials) {
    54. return encryptCredentials.equals(createCredentials(credentials, salt));
    55. }
    56. public static void main(String[] args) {
    57. //盐
    58. String salt = createSalt();
    59. System.out.println(salt);
    60. System.out.println(salt.length());
    61. //凭证+盐加密后得到的密码
    62. String credentials = createCredentials("123456", salt);
    63. System.out.println(credentials);
    64. System.out.println(credentials.length());
    65. boolean b = checkCredentials("123456", salt, credentials);
    66. System.out.println(b);
    67. }
    68. }

    假设用户:zhangsan

    用户密码:zhangsan

    传到后台:1.生成随机的盐     2.利用zhangsan原始密码+生成随机的盐 得到加密后的密码

                       3.再insert

  • 相关阅读:
    servlet相关
    php apache 后台超时设置
    LabVIEW合并VI
    直播会议一体机安卓主板_5G智能会议一体机双屏异显设计
    [MIT 6.1810]Lab7-networking
    ReactDOM.render在react源码中执行之后发生了什么?
    探究WPF中文字模糊的问题:TextOptions的用法
    学习记忆——宫殿篇——记忆宫殿——记忆桩——学校
    springMvc42-处理静态资源
    进程地址空间
  • 原文地址:https://blog.csdn.net/weixin_67450855/article/details/126549403