• shiro认证


    目录

    一、盐加密

    二、Shiro认证

    1、pom依赖

     2、web.xml配置

    3、通过逆向工程将五张表生成对应的model、mapper

    4、mapper层

    5、web层:UserController

            6、biz层

    7、Myrealm.java

    8、applicationContext-shiro.xml

    9、导入上一篇博客的jsp文件夹


    一、盐加密

    PasswordHelper

    1. package com.liaoxin.ssm.util;
    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. }

     

    二、Shiro认证

    1、pom依赖

    1. <groupId>org.apache.shirogroupId>
    2. <artifactId>shiro-coreartifactId>
    3. <version>1.3.2version>
    4. <dependency>
    5. <groupId>org.apache.shirogroupId>
    6. <artifactId>shiro-webartifactId>
    7. <version>1.3.2version>
    8. dependency>
    9. <dependency>
    10. <groupId>org.apache.shirogroupId>
    11. <artifactId>shiro-springartifactId>
    12. <version>1.3.2version>
    13. dependency>

     2、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>

    3、通过逆向工程将五张表生成对应的model、mapper

    4、mapper层

    ①UserMapper.xml

    1. "1.0" encoding="UTF-8" ?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3. <mapper namespace="com.liaoxin.ssm.mapper.UserMapper" >
    4. <resultMap id="BaseResultMap" type="com.liaoxin.ssm.model.User" >
    5. <constructor >
    6. <idArg column="userid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    7. <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
    8. <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />
    9. <arg column="salt" jdbcType="VARCHAR" javaType="java.lang.String" />
    10. <arg column="createdate" jdbcType="TIMESTAMP" javaType="java.util.Date" />
    11. constructor>
    12. resultMap>
    13. <sql id="Base_Column_List" >
    14. userid, username, password, salt, createdate
    15. sql>
    16. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    17. select
    18. <include refid="Base_Column_List" />
    19. from t_shiro_user
    20. where userid = #{userid,jdbcType=INTEGER}
    21. select>
    22. <select id="queryByName" resultType="com.liaoxin.ssm.model.User" parameterType="java.lang.String">
    23. select
    24. <include refid="Base_Column_List" />
    25. from t_shiro_user
    26. where userName = #{userName}
    27. select>
    28. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    29. delete from t_shiro_user
    30. where userid = #{userid,jdbcType=INTEGER}
    31. delete>
    32. <insert id="insert" parameterType="com.liaoxin.ssm.model.User" >
    33. insert into t_shiro_user (userid, username, password,
    34. salt, createdate)
    35. values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
    36. #{salt,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP})
    37. insert>
    38. <insert id="insertSelective" parameterType="com.liaoxin.ssm.model.User" >
    39. insert into t_shiro_user
    40. <trim prefix="(" suffix=")" suffixOverrides="," >
    41. <if test="userid != null" >
    42. userid,
    43. if>
    44. <if test="username != null" >
    45. username,
    46. if>
    47. <if test="password != null" >
    48. password,
    49. if>
    50. <if test="salt != null" >
    51. salt,
    52. if>
    53. <if test="createdate != null" >
    54. createdate,
    55. if>
    56. trim>
    57. <trim prefix="values (" suffix=")" suffixOverrides="," >
    58. <if test="userid != null" >
    59. #{userid,jdbcType=INTEGER},
    60. if>
    61. <if test="username != null" >
    62. #{username,jdbcType=VARCHAR},
    63. if>
    64. <if test="password != null" >
    65. #{password,jdbcType=VARCHAR},
    66. if>
    67. <if test="salt != null" >
    68. #{salt,jdbcType=VARCHAR},
    69. if>
    70. <if test="createdate != null" >
    71. #{createdate,jdbcType=TIMESTAMP},
    72. if>
    73. trim>
    74. insert>
    75. <update id="updateByPrimaryKeySelective" parameterType="com.liaoxin.ssm.model.User" >
    76. update t_shiro_user
    77. <set >
    78. <if test="username != null" >
    79. username = #{username,jdbcType=VARCHAR},
    80. if>
    81. <if test="password != null" >
    82. password = #{password,jdbcType=VARCHAR},
    83. if>
    84. <if test="salt != null" >
    85. salt = #{salt,jdbcType=VARCHAR},
    86. if>
    87. <if test="createdate != null" >
    88. createdate = #{createdate,jdbcType=TIMESTAMP},
    89. if>
    90. set>
    91. where userid = #{userid,jdbcType=INTEGER}
    92. update>
    93. <update id="updateByPrimaryKey" parameterType="com.liaoxin.ssm.model.User" >
    94. update t_shiro_user
    95. set username = #{username,jdbcType=VARCHAR},
    96. password = #{password,jdbcType=VARCHAR},
    97. salt = #{salt,jdbcType=VARCHAR},
    98. createdate = #{createdate,jdbcType=TIMESTAMP}
    99. where userid = #{userid,jdbcType=INTEGER}
    100. update>
    101. mapper>

     ②UserMapper.java

    1. package com.liaoxin.ssm.mapper;
    2. import com.liaoxin.ssm.model.User;
    3. public interface UserMapper {
    4. int deleteByPrimaryKey(Integer userid);
    5. int insert(User record);
    6. int insertSelective(User record);
    7. User selectByPrimaryKey(Integer userid);
    8. User queryByName(String userName);
    9. int updateByPrimaryKeySelective(User record);
    10. int updateByPrimaryKey(User record);
    11. }

    5、web层:UserController

    1. package com.liaoxin.ssm.web;
    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.ServletException;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. /**
    12. * @author liaoxin
    13. * @create 2022-08-25 18:30
    14. */
    15. @Controller
    16. public class UserController {
    17. @RequestMapping("/login")
    18. public String login(HttpServletRequest request, HttpServletResponse response){
    19. try{
    20. String username=request.getParameter("username");
    21. String password = request.getParameter("password");
    22. UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
    23. Subject subject = SecurityUtils.getSubject();
    24. subject.login(usernamePasswordToken);
    25. return "main";
    26. }catch (Exception e){
    27. request.setAttribute("message","您的用户名或者密码有误");
    28. return "login";
    29. }
    30. }
    31. @RequestMapping("/logout")
    32. public String logout(HttpServletRequest request, HttpServletResponse response){
    33. try{
    34. Subject subject = SecurityUtils.getSubject();
    35. subject.logout();
    36. return "login";
    37. }catch (Exception e){
    38. request.setAttribute("message","您的用户名或者密码有误");
    39. return "login";
    40. }
    41. }
    42. }

    6、biz层

    ①UserBiz

    1. package com.liaoxin.ssm.biz;
    2. import com.liaoxin.ssm.model.User;
    3. /**
    4. * @author liaoxin
    5. * @create 2022-08-25 18:06
    6. */
    7. public interface UserBiz {
    8. int deleteByPrimaryKey(Integer userid);
    9. int insert(User record);
    10. int insertSelective(User record);
    11. User selectByPrimaryKey(Integer userid);
    12. User queryByName(String userName);
    13. int updateByPrimaryKeySelective(User record);
    14. int updateByPrimaryKey(User record);
    15. }

    ②UserBizImpl

    1. package com.liaoxin.ssm.biz.impl;
    2. import com.liaoxin.ssm.biz.UserBiz;
    3. import com.liaoxin.ssm.mapper.UserMapper;
    4. import com.liaoxin.ssm.model.User;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. /**
    8. * @author liaoxin
    9. * @create 2022-08-25 18:08
    10. */
    11. @Service("UserService")
    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 queryByName(String userName) {
    33. return userMapper.queryByName(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. }

    7、Myrealm.java

    1. package com.liaoxin.ssm.shiro;
    2. import com.liaoxin.ssm.biz.UserBiz;
    3. import com.liaoxin.ssm.model.User;
    4. import org.apache.shiro.authc.AuthenticationException;
    5. import org.apache.shiro.authc.AuthenticationInfo;
    6. import org.apache.shiro.authc.AuthenticationToken;
    7. import org.apache.shiro.authc.SimpleAuthenticationInfo;
    8. import org.apache.shiro.authz.AuthorizationInfo;
    9. import org.apache.shiro.realm.AuthorizingRealm;
    10. import org.apache.shiro.subject.PrincipalCollection;
    11. import org.apache.shiro.util.ByteSource;
    12. /**
    13. * @author liaoxin
    14. * @create 2022-08-25 18:16
    15. */
    16. public class Myrealm extends AuthorizingRealm {
    17. private UserBiz userBiz;
    18. public UserBiz getUserBiz() {
    19. return userBiz;
    20. }
    21. public void setUserBiz(UserBiz userBiz) {
    22. this.userBiz = userBiz;
    23. }
    24. @Override
    25. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    26. return null;
    27. }
    28. @Override
    29. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    30. System.out.println("身份验证...");
    31. String username = token.getPrincipal().toString();
    32. String password = token.getCredentials().toString();
    33. User user = userBiz.queryByName(username);
    34. AuthenticationInfo info=new SimpleAuthenticationInfo(
    35. user.getUsername(),
    36. user.getPassword(),
    37. ByteSource.Util.bytes(user.getSalt()),
    38. this.getName()
    39. );
    40. return info;
    41. }
    42. }

    8、applicationContext-shiro.xml

    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.javaxl.ssm.shiro.MyRealm">
    6. <property name="shiroUserService" ref="shiroUserService" />
    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>

    9、导入上一篇博客的jsp文件

     

  • 相关阅读:
    什么是Mock?为什么要使用Mock呢?
    中断机制-interrupt和isInterrupted源码分析、中断协商案例
    关于C语言的一些尘封记忆的唤醒
    UDP程序设计
    SpringBoot篇---第三篇
    shiro集成 spring-加密md5配置--权限管理-shiro中的session 等等!!
    链表的归并排序-LeetCode(Python版)
    爬虫-(4)
    蓝桥杯KMP总结
    token
  • 原文地址:https://blog.csdn.net/qq_44247968/article/details/126541208