前言

之前看到satoken(文档),感觉很方便。之前我用shiro+redis+jwt(或者session)遇到的一些问题,用这个感觉都不是问题,很轻易就能解决,比如:多端登录可以不用写realm、移动端保持长期登录、token自动刷新、超过系统空闲时间重新登录等。
在这里插入图片描述
功能还是比较全面的,下面主要是会写一些比较常用的。

一、大概需求

web登录,有个闲置时间设置:1 30分钟未发送请求,重新登录,0 无限制。
角色菜单权限控制。

一、框架搭建

1、引入依赖、yml文件

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-boot.version>2.5.6</spring-boot.version>
    <sa-token-version>1.29.0</sa-token-version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-to-slf4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <!-- mysql 驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
        <scope>runtime</scope>
    </dependency>
    <!-- mybatis_plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3</version>
    </dependency>

    <!-- hutool工具类 -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.7.22</version>
    </dependency>

    <!-- 提供Redis连接池 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>

    <!-- pagehelper分页插件 -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.9</version>
        <exclusions>
            <exclusion>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- sa-token权限认证框架 -->
    <dependency>
        <groupId>cn.dev33</groupId>
        <artifactId>sa-token-spring-boot-starter</artifactId>
        <version>${sa-token-version}</version>
    </dependency>
    <!-- Sa-Token 整合 Redis (使用jackson序列化方式) -->
    <dependency>
        <groupId>cn.dev33</groupId>
        <artifactId>sa-token-dao-redis-jackson</artifactId>
        <version>${sa-token-version}</version>
    </dependency>
    <!-- Sa-Token插件:权限缓存与业务缓存分离 -->
    <dependency>
        <groupId>cn.dev33</groupId>
        <artifactId>sa-token-alone-redis</artifactId>
        <version>${sa-token-version}</version>
    </dependency>

</dependencies>

server:
  port: 8081

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/satoken_db?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
    username: root
    password: root
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver

  redis:
    host: "127.0.0.1"
    port: 6379
    timeout: 10s
    password: 123456
    database: 0
    lettuce:
      pool:
        max-active: -1
        max-wait: -1
        max-idle: 16
        min-idle: 8

  main:
    allow-bean-definition-overriding: true

  servlet:
    multipart:
      max-file-size: -1
      max-request-size: -1

  aop:
    auto: true

# Sa-Token配置
sa-token:
  # token名称 (同时也是cookie名称)
  token-name: sa-token-authorization
  # token有效期,单位s 默认30天, -1代表永不过期
  timeout: 3600
  # token风格
  token-style: random-32
  # 是否尝试从 header 里读取 Token
  is-read-head: true
  # 是否开启自动续签
  auto-renew: true
  # 临时有效期,单位s,例如将其配置为 1800 (30分钟),代表用户如果30分钟无操作,则此Token会立即过期
  activity-timeout: 1800
  # 是否允许同一账号并发登录 (为true时允许一起登录, 为false时同端互斥) 
  is-concurrent: true
  # 配置 Sa-Token 单独使用的 Redis 连接
  alone-redis:
    # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    # Redis服务器连接密码(默认为空)
    password: 123456
    # 连接超时时间
    timeout: 10s


mybatis-plus:
  mapper-locations: classpath:mapper/*/*.xml
  type-aliases-package: com.entity.sys,;com.common.base
  global-config:
    db-config:
      id-type: auto
      field-strategy: NOT_EMPTY
      db-type: MYSQL
  configuration:
    map-underscore-to-camel-case: true
    call-setters-on-nulls: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

在这里插入图片描述

2、Config 和 Interceptor

@Configuration
@EnableWebMvc
public class GlobalCorsConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String path = System.getProperty("user.dir") + "\\upload\\";
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:"+path).addResourceLocations("classpath:/resources/");
    }

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册Sa-Token的路由拦截器
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/sys/login","/sys/getCode","/sys/getKey","/api/favicon.ico","/upload/**");
        //registry.addInterceptor(new SaRouteInterceptor((req, resp, handler) -> {
        //    SaRouter.match("/sys/login","/sys/getCode","/sys/getKey","/favicon.ico","/upload/**");
        //})).addPathPatterns("/**");
    }

    /**
     * 允许跨域调用的过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOriginPattern("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600)
        .exposedHeaders();
    }
}
LoginInterceptor 登录拦截
/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 删除redis缓存
     */
    private void delCache(String tokenValue,String loginId){
        RedisUtil redisUtil= SpringUtil.getBean(RedisUtil.class);
        String lastActivity = BaseConstant.cachePrefix+"last-activity:"+tokenValue;
        String session = BaseConstant.cachePrefix+"session:"+loginId;
        String token = BaseConstant.tokenCachePrefix+tokenValue;
        if (redisUtil.hasKey(lastActivity)){
            redisUtil.del(lastActivity);
        }
        if (redisUtil.hasKey(session)){
            redisUtil.del(session);
        }
        if (redisUtil.hasKey(token)){
            redisUtil.del(token);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        response.setHeader("Access-Control-Allow-Origin", (request).getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        // 获取当前token(这个token获取的是请求头的token,也可以用 request 获取)
        String tokenValue = StpUtil.getTokenValue();
        // 根据token获取用户id(这里如果找不到id直接返回null,不会报错)
        String loginId = (String) StpUtil.getLoginIdByToken(tokenValue);
        //判断token是否过期:如果token的有效期还没到,但是activity-timeout已经过了,那么token就会失效
        if (!StpUtil.isLogin()){
            ResultVo resultVo = new ResultVo();
            resultVo.setCode(1003);
            resultVo.setMessage("用户未登录,请进行登录");
            response.getWriter().write(JSONUtil.toJsonStr(resultVo));
            //token已经过期,但是redis中可能还存在,所以要删除
            delCache(tokenValue,loginId);
            return false;
        }
        
        /**  记:2022-06-24 修改  开始  */
		//判断token的创建时间是否大于2小时,如果是的话则需要刷新token
		long time = System.currentTimeMillis() - StpUtil.getSession().getCreateTime();
        long hour = time/1000/(60 * 60);
        if (hour>2){
        	//这里要生成新的token的话,要先退出再重新登录
        	//根据当前登录id(和设备)退出登录
	        //StpUtil.logout(loginId,loginDevice);
	        StpUtil.logout(loginId);
	        //然后再重新登录,生成新的token
	        //StpUtil.login(loginId,loginDevice);
	        StpUtil.login(loginId);
	        String newToken = StpUtil.getTokenValue();
            System.err.println("生成的新的token:"+ newToken);
            response.setHeader("sa-token-authorization", newToken);
        }
        /**  记:2022-06-24 修改  结束  */

        // 获取过期时间
        long tokenTimeout = StpUtil.getTokenTimeout();
        //token没过期,过期时间不是-1的时候,每次请求都刷新过期时间
        if (tokenTimeout != -1){
            SaTokenDao saTokenDao = SaManager.getSaTokenDao();
            saTokenDao.updateSessionTimeout(StpUtil.getSession().getId(),3600);
            saTokenDao.updateTimeout(BaseConstant.tokenCachePrefix+tokenValue,3600);
            saTokenDao.updateTimeout(BaseConstant.cachePrefix+"last-activity:"+tokenValue,3600);
        }
        // 检查通过后继续续签
        //StpUtil.updateLastActivityToNow();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}

在这里插入图片描述

PermissionInterface 权限验证
/**
 * 自定义权限验证接口扩展
 */
@Component
public class PermissionInterface implements StpInterface {

    @Resource
    private SysMenuService sysMenuService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> list = new ArrayList<String>();
        // 2. 遍历角色列表,查询拥有的权限码
        for (String roleId : getRoleList(loginId, loginType)) {
            SysQuery queryVo = new SysQuery();
            queryVo.setId(roleId);
            //查询角色和权限(这里根据业务自行查询)
            List<SysMenu> menuList = sysMenuService.selectPermsByRoleId(queryVo);
            List<String> collect = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
            list.addAll(collect);
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> list = new ArrayList<>();
        // 这里获取用户角色可以直接从session中获取,也可以去数据库查询
        SysUser user = (SysUser) StpUtil.getSession().get("user");
        list.add(user.getRoleId());
        return list;
    }
}

3、SysLoginController登录

@RestController
@RequestMapping("/sys")
public class SysLoginController {

    @Resource
    private SysSafeService sysSafeService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private RedisUtil redisUtil;

    /** 密码最大错误次数 */
    private int ERROR_COUNT = 3;

     /**
     * 登录:
     * 多个终端登录可以写不同的登录接口,分别设置登录的设备。
     * 也可以写一个统一的接口,在 request 中设置登录终端标识,根据这个标识来设置登录的设备。
     * 退出登录同理
     * */
    @PostMapping("/login")
    public ResultVo login(String userName, String password, String code, HttpServletRequest request){
        try {
            code = code.toUpperCase();
            Object verCode = redisUtil.get(BaseConstant.verCode+code);
            if (null == verCode) {
                return ResultUtil.error("验证码已失效,请重新输入");
            }
            String verCodeStr = verCode.toString();
            if (verCodeStr == null || StrUtil.isEmpty(code) || !verCodeStr.equalsIgnoreCase(code)) {
                return ResultUtil.error("验证码错误");
            }else if (!redisUtil.hasKey(BaseConstant.verCode+code)) {
                return ResultUtil.error("验证码已过期,请重新输入");
            }else {
                redisUtil.del(BaseConstant.verCode+code);
            }
            //私钥解密
            userName = RSAUtil.decrypt(userName);
            password = RSAUtil.decrypt(password);

            SysSafe safe = sysSafeService.list().get(0);
            //校验用户、用户密码
            SysUser user = passwordErrorNum(userName, password,safe);
            String oldToken = StpUtil.getTokenValueByLoginId(user.getId()); // 先根据登录id获取token
            if (StrUtil.isNotBlank(oldToken)){
                StpUtil.logout(user.getId()); // 如果token不为空,先退出登录
            }
            // StpUtil.login()可以设置登录的设备,比如web端登录,或者移动端登录,只需要设置device即可
            // StpUtil.login(user.getId(),"WEB");
            StpUtil.login(user.getId());
            
            String tokenValue = StpUtil.getTokenValue();
            //将登录用户信息设置到session中
            StpUtil.getSession().set("user",user);
            int i = safe.getIdleTimeSetting();
            //如果系统闲置时间为0,设置token和session永不过期
            if (i==0){
            	//修改 token、session、activity-timeout 的过期时间
	            SaTokenDao saTokenDao = SaManager.getSaTokenDao();
	            SaTokenConfig config = SaManager.getConfig();
                saTokenDao.updateSessionTimeout(StpUtil.getSession().getId(),-1);
                saTokenDao.updateTimeout(BaseConstant.tokenCachePrefix+tokenValue ,-1);
                saTokenDao.updateTimeout(BaseConstant.cachePrefix+"last-activity:"+tokenValue ,-1);
                config.setActivityTimeout(-1);
            }
            return ResultUtil.success(tokenValue);
        } catch (ExceptionVo e) {
            return ResultUtil.error(e.getCode(),e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("未知异常");
        }
    }

	@PostMapping("/test")
    public ResultVo test(){
        Map<String,Object> map = new HashMap<>();
        SaSession session = StpUtil.getSession();
        //获取用户信息
        map.put("user",session.get("user"));
        //获取权限集合
        map.put("permission",StpUtil.getPermissionList());
        //获取token信息
        map.put("tokenInfo",StpUtil.getTokenInfo());
        return ResultUtil.success(map);
    }

    /** 获取验证码 */
    @GetMapping(value = "/getCode")
    public void getCode(HttpServletResponse response) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            RandomGenerator randomGenerator = new RandomGenerator(BaseConstant.captcha, 4);
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 42,4,50);
            lineCaptcha.setGenerator(randomGenerator);
            BufferedImage image = lineCaptcha.getImage();
            OutputStream out = response.getOutputStream();
            redisUtil.set(BaseConstant.verCode+lineCaptcha.getCode(), lineCaptcha.getCode(), 60);
            ImageIO.write(image, "png", out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 退出登录 */
    @DeleteMapping("/logout")
    public ResultVo logout(HttpServletRequest request){
        //退出
        StpUtil.logout();
        //根据token退出
        //String token = request.getHeader(BaseConstant.tokenHeader);
        //StpUtil.logoutByTokenValue(token);
        //根据用户id和登录设备退出
        //StpUtil.logout(StpUtil.getLoginId(),"WEB");
        return ResultUtil.success("退出登录成功");
    }

    /**
     * 产生public key
     */
    @GetMapping("/getKey")
    public ResultVo getKey() {
        String publicKey = RSAUtil.getPublicKey();
        System.out.println(publicKey);
        return ResultUtil.success(publicKey);
    }

    /**
     * 判断账号是否锁定
     */
    private boolean lockedUser(long currentTime,String userName){
        boolean flag = false;
        if (redisUtil.hasKey(BaseConstant.ERROR_COUNT+userName)){
            long loginTime = Long.parseLong(redisUtil.hget(BaseConstant.ERROR_COUNT+userName, "loginTime").toString());
            int i = Integer.parseInt(redisUtil.hget(BaseConstant.ERROR_COUNT+userName,"errorNum").toString());
            if (i >= ERROR_COUNT && currentTime < loginTime){
                Duration between = LocalDateTimeUtil.between(LocalDateTimeUtil.of(currentTime), LocalDateTimeUtil.of(loginTime));
                throw new ExceptionVo(1004,"账号锁定中,还没到允许登录的时间,请"+between.toMinutes()+"分钟后再尝试");
            }else{
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 密码错误次数验证
     */
    private SysUser passwordErrorNum(String userName,String password,SysSafe sysSafe) throws InvalidKeySpecException, NoSuchAlgorithmException {
        //查询用户
        SysUser user = sysUserService.getUserByName(userName);
        if (null == user){
            throw new ExceptionVo(1001,"用户不存在");
        }
        //根据前端输入的密码(明文),和加密的密码、盐值进行比较,判断输入的密码是否正确
        boolean authenticate = EncryptionUtil.authenticate(password, user.getPassword(), user.getSalt());
        if (authenticate) {
            //密码正确错误次数清零
            redisUtil.del(BaseConstant.ERROR_COUNT+userName);
        } else {
            long currentTime = System.currentTimeMillis();
            //判断账号是否锁定
            boolean flag = lockedUser(currentTime, userName);

            //错误3次,锁定15分钟后才可登陆 允许时间加上定义的登陆时间(毫秒)
            String str = "15";
            long timeStamp = System.currentTimeMillis()+900000;
            //密码登录限制(0:连续错3次,锁定账号15分钟。1:连续错5次,锁定账号30分钟)
            if (sysSafe.getPwdLoginLimit()==1){
                ERROR_COUNT = 5;
                str = "30";
                timeStamp = System.currentTimeMillis()+1800000;
            }
            //密码登录限制(0:连续错3次,锁定账号15分钟。1:连续错5次,锁定账号30分钟)
            if (redisUtil.hasKey(BaseConstant.ERROR_COUNT+userName)){
                int i = Integer.parseInt(redisUtil.hget(BaseConstant.ERROR_COUNT+userName,"errorNum").toString());
                if (flag && i==ERROR_COUNT){
                    redisUtil.hset(BaseConstant.ERROR_COUNT+userName,"errorNum",1);
                }else {
                    redisUtil.hincr(BaseConstant.ERROR_COUNT+userName,"errorNum",1);
                }
                redisUtil.hset(BaseConstant.ERROR_COUNT+userName,"loginTime",timeStamp);
            }else {
                Map<String,Object> map = new HashMap<>();
                map.put("errorNum",1);
                map.put("loginTime",timeStamp);
                redisUtil.hmset(BaseConstant.ERROR_COUNT+userName, map, -1);
            }
            int i = Integer.parseInt(redisUtil.hget(BaseConstant.ERROR_COUNT+userName,"errorNum").toString());
            if (i==ERROR_COUNT){
                throw new ExceptionVo(1004,"您的密码已错误"+ERROR_COUNT+"次,现已被锁定,请"+str+"分钟后再尝试");
            }
            throw new ExceptionVo(1000,"密码错误,总登录次数"+ERROR_COUNT+"次,剩余次数: " + (ERROR_COUNT-i));
        }
        return user;
    }
}

在这里插入图片描述

4、RSAUtil 非对称加密、解密工具类

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * RSA非对称加密、解密工具类
 */
public class RSAUtil {

    private static final KeyPair keyPair = initKey();

    /**
     * RSA非对称加密,随机生成密钥对
     */
    private static KeyPair initKey() {
        try {
            // 产生用于安全加密的随机数
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(1024, new SecureRandom());
            return generator.generateKeyPair();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 产生public key
     */
    public static String getPublicKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // getEncoded():返回key的原始编码形式
        return new String(Base64.encodeBase64(publicKey.getEncoded()));
    }

    /**
     * RAS非对称加密: 公钥加密
     * @param str 需要加密的字符串
     * @return 密文
     */
    public static String encrypt(String str) {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(getPublicKey());
        RSAPublicKey pubKey;
        String outStr = null;
        try {
            pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        } catch (InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //RSA加密
        return outStr;
    }

    /**
     * RSA私钥解密
     * @param str 加密的字符串
     * @return 铭文
     */
    public static String decrypt(String str) {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
        PrivateKey privateKey = keyPair.getPrivate();
        //base64编码的私钥
        byte[] decoded = privateKey.getEncoded();
        RSAPrivateKey priKey;
        //RSA解密
        Cipher cipher;
        String outStr = null;
        try {
            priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return outStr;
    }
}

5、EncryptionUtil 密码盐值加密工具类

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;


/**
 * 密码盐值加密工具类
 */
public class EncryptionUtil {

    public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";

    /**
     * 盐的长度
     */
    public static final int SALT_BYTE_SIZE = 16;

    /**
     * 生成密文的长度
     */
    public static final int HASH_BIT_SIZE = 64;

    /**
     * 迭代次数
     */
    public static final int PBKDF2_ITERATIONS = 1000;

    /**
     * 验证输入的password是否正确
     * @param attemptedPassword 待验证的password
     * @param encryptedPassword 密文
     * @param salt 盐值
     */
    public static boolean authenticate(String attemptedPassword, String encryptedPassword, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 用同样的盐值对用户输入的password进行加密
        String encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);
        // 把加密后的密文和原密文进行比較,同样则验证成功。否则失败
        return encryptedAttemptedPassword.equals(encryptedPassword);
    }

    /**
     * 生成密文
     * @param password 明文password
     * @param salt 盐值
     */
    public static String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeySpec spec = new PBEKeySpec(password.toCharArray(), fromHex(salt), PBKDF2_ITERATIONS, HASH_BIT_SIZE);
        SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
        return toHex(f.generateSecret(spec).getEncoded());
    }

    /**
     * 通过提供加密的强随机数生成器 生成盐
     */
    public static String generateSalt() throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[SALT_BYTE_SIZE];
        random.nextBytes(salt);
        return toHex(salt);
    }

    /**
     * 十六进制字符串转二进制字符串
     * @param hex the hex string
     */
    private static byte[] fromHex(String hex) {
        byte[] binary = new byte[hex.length() / 2];
        for (int i = 0; i < binary.length; i++) {
            binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return binary;
    }

    /**
     * 二进制字符串转十六进制字符串
     * @param array the byte array to convert
     */
    private static String toHex(byte[] array) {
        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
        int paddingLength = (array.length * 2) - hex.length();
        if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex;
        else return hex;
    }

}

2022.06.24修改

LoginInterceptor 登录拦截器修改

原:

/*
  long time = System.currentTimeMillis() - StpUtil.getSession().getCreateTime();
  long hour = time/1000/(60 * 60);
  System.out.println(hour);
  if (hour>2){
  	// 本来这里我是想要生成一个新token,然后我找了下没有直接生成token的方法;
  	// 之后我看了它的需求墙,作者说每次调用登录方法都会自动刷新并生成新的token。
  	// 但是我这里调用登录方法,发现token并没有改变,还是原来的那个token,不知道是我方式用错了还是少了代码。所以这个地方存疑,有知道的小伙伴可以评论区留言。
  	StpUtil.login(loginId);
      System.err.println("生成的新的token:"+StpUtil.getTokenValue());
      response.setHeader("sa-token-authorization", StpUtil.getTokenValue());
  }*/

修改:

/**  记:2022-06-24 修改  开始  */
//判断token的创建时间是否大于2小时,如果是的话则需要刷新token
long time = System.currentTimeMillis() - StpUtil.getSession().getCreateTime();
long hour = time/1000/(60 * 60);
if (hour>2){
	//这里要生成新的token的话,要先退出再重新登录
	//根据当前登录id(和设备)退出登录
	//StpUtil.logout(loginId,loginDevice);
	StpUtil.logout(loginId);
	//然后再重新登录,生成新的token
	//StpUtil.login(loginId,loginDevice);
	StpUtil.login(loginId);
	String newToken = StpUtil.getTokenValue();
	System.err.println("生成的新的token:"+ newToken);
	response.setHeader("sa-token-authorization", newToken);
}
/**  记:2022-06-24 修改  结束  */

源码

有完整的实现案例和数据库文件。

希望大家多多点赞支持一下(不要光收藏不点赞啊呜呜呜)

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐