详解Springboot整合Shiro加盐加散列实现登陆注册小案例

前言

Springboot和Shiro的基本介绍我就不多说了,能看到这篇文章的相信也都会用。这篇文章主要是分享一下我在学习Shiro和Springboot的整合的小阶段。目前是复习,很感谢B站的up主——编程不良人的视频让我有了一个学习Shiro的基本方向。
目前是实现了用户认证的功能。

依赖

整合的时候使用的是jsp,其实和thymeleaf一个道理,而且不涉及到作用域传值。我们需要导入的依赖有:mysql、mybatis、jsp、jstl、shiro-springboot、test、web、lombok以及热部署
我就直接贴代码了。

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-devtoolsartifactId>
    <scope>runtimescope>
    <optional>trueoptional>
dependency>
<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
dependency>
<dependency>
    <groupId>org.apache.shirogroupId>
    <artifactId>shiro-spring-boot-starterartifactId>
    <version>1.5.3version>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.4version>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druid-spring-boot-starterartifactId>
    <version>1.1.24version>
dependency>

<dependency>
    <groupId>org.apache.tomcat.embedgroupId>
    <artifactId>tomcat-embed-jasperartifactId>
dependency>
<dependency>
    <groupId>jstlgroupId>
    <artifactId>jstlartifactId>
    <version>1.2version>
dependency>

上面的依赖就不多解释了,应该都认识。

数据库建表

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `salt` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

SET FOREIGN_KEY_CHECKS = 1;

思路设计

首先得先准备三个页面:登录、注册以及主页
设计的思路是我们需要去拦截主页,不让用户直接访问到,并且跳转到登录页面。那我们就需要去拦截这个路由。
在注册时候,通过我们写的加盐工具类,用随机生成的盐去将密码加密保存在数据库中,并且设置好散列的次数。
登录时,需要手动设置realm的加盐策略以及散列的次数。
话不多说直接上代码。

yml配置
spring:
  application:
    name: shiro
  mvc:
    view:
      prefix: /
      suffix: .jsp
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql:///shiro?characterEncoding=UTF-8&serverTimezone=GMT
    username: root
    password: 1234
server:
  port: 8080
  servlet:
    context-path: /shiro
mybatis:
  type-aliases-package: com.zxy.pojo
  mapper-locations: classpath:mapper/*.xml
盐工具类
public static String getSalt(int n){
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }
模拟界面

index.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>



    
    
    
    Document


系统主页v1.0

退出登录

login.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>



    
    
    
    登录


用户登录

用户名:
密码:

register.jsp

<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>



    
    
    
    注册


用户注册

用户名:
密码:
实体类
package com.zxy.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @Author Zxy
 * @Date 2021/1/8 17:31
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class User {
    private Integer id;
    private String username;
    private String password;
    private String salt;
}
数据层
package com.zxy.mapper;

import com.zxy.pojo.User;

/**
 * @Author Zxy
 * @Date 2021/1/8 17:33
 * @Version 1.0
 */
public interface UserMapper {
    void save(User user);

    User findByUsername(String username);
}



<mapper namespace="com.zxy.mapper.UserMapper">
    <insert id="save">
        insert into t_user
        values (#{id}, #{username}, #{password}, #{salt})
    insert>
    <select id="findByUsername" resultType="com.zxy.pojo.User">
        select id,username,password,salt
        from t_user
        where username = #{username}
    select>
mapper>
服务层
package com.zxy.service;

import com.zxy.pojo.User;

/**
 * @Author Zxy
 * @Date 2021/1/8 17:35
 * @Version 1.0
 */
public interface UserService {
    void register(User user);

    User findByUsername(String username);
}

package com.zxy.service;

import com.zxy.mapper.UserMapper;
import com.zxy.pojo.User;
import com.zxy.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author Zxy
 * @Date 2021/1/8 17:35
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public void register(User user) {
        // 处理业务

        // 明文密码进行md5+salt+hash散列
        // 1、生成随机盐
        String salt = SaltUtils.getSalt(8);
        // 2、将随机盐保存到数据库
        user.setSalt(salt);
        // 3、明文密码进行md5+salt+hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        mapper.save(user);
    }

    @Override
    public User findByUsername(String username) {
        return mapper.findByUsername(username);
    }
}

控制层

package com.zxy.controller;

import com.zxy.pojo.User;
import com.zxy.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
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;
/**
 * @Author Zxy
 * @Date 2021/1/8 17:05
 * @Version 1.0
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService service;
    /*退出登录*/
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
    // 用来处理身份认证(登录)
    @RequestMapping("/login")
    public String login(String username, String password) {
        // 获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
            e.printStackTrace();
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
            e.printStackTrace();
        }
        return "redirect:/login.jsp";
    }
    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String register(User user) {
        try {
            service.register(user);
            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }
}

shiro自定义配置层
package com.zxy.config;

import com.zxy.shiro.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
/**
 * @Author Zxy
 * @Date 2021/1/8 16:21
 * @Version 1.0
 * 用来整合shiro框架相关的配置类
 */
@Configuration
public class ShiroConfig {
    // 创建shiroFilter  负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 配置系统的受限资源
        HashMap<String, String> map = new HashMap<>();
        // 不受限的资源设置成公共资源
        map.put("/user/login", "anon");
        map.put("/user/register", "anon");
        map.put("/register.jsp", "anon");
        // 通配符会拦截所有除了setLoginUrl方法的路由
        map.put("/**", "authc"); // authc代表请求这个资源需要认证和授权
        // 默认的认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        // 配置系统的公共资源
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    // 创建安全管理器
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("realm") Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    // 创建自定义realm  在自定义realm中设置密码凭证匹配器以及哈希散列次数
    @Bean(name = "realm")
    public Realm getRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        // 修改凭证校验匹配器
        // 设置realm使用hash凭证
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置哈希算法的名字
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置散列的次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        return customerRealm;
    }

}

以上就是所有的源码,需要的小伙伴自取。如果对你有帮助,不妨把你的爱心点一点。

你可能感兴趣的:(技术杂谈,shiro,mybatis,hash,springboot,boot-shiro)