栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SaToken使用】springboot+redis+satoken权限认证

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SaToken使用】springboot+redis+satoken权限认证

前言

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

功能还是比较全面的,下面主要是会写一些比较常用的。

一、大概需求

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

一、框架搭建 1、引入依赖、yml文件

    1.8
    UTF-8
    UTF-8
    2.5.6
    1.29.0



    
        org.springframework.boot
        spring-boot-starter
        
            
                org.apache.logging.log4j
                log4j-api
            
            
                org.apache.logging.log4j
                log4j-to-slf4j
            
        
    
    
        org.springframework.boot
        spring-boot-starter-aop
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-freemarker
    
    
    
        org.projectlombok
        lombok
        true
    

    
    
        mysql
        mysql-connector-java
        8.0.11
        runtime
    
    
    
        com.baomidou
        mybatis-plus-boot-starter
        3.4.3
    

    
    
        cn.hutool
        hutool-all
        5.7.22
    

    
    
        org.apache.commons
        commons-pool2
    

    
    
        com.github.pagehelper
        pagehelper-spring-boot-starter
        1.2.9
        
            
                org.mybatis
                mybatis
            
            
                org.mybatis
                mybatis-spring
            
        
    

    
    
        cn.dev33
        sa-token-spring-boot-starter
        ${sa-token-version}
    
    
    
        cn.dev33
        sa-token-dao-redis-jackson
        ${sa-token-version}
    
    
    
        cn.dev33
        sa-token-alone-redis
        ${sa-token-version}
    





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
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOriginPattern("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("
public class LoginInterceptor implements HandlerInterceptor {

    
    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;
        }
        
        
		//判断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);
        }
        

        // 获取过期时间
        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 getPermissionList(Object loginId, String loginType) {
        List list = new ArrayList();
        // 2. 遍历角色列表,查询拥有的权限码
        for (String roleId : getRoleList(loginId, loginType)) {
            SysQuery queryVo = new SysQuery();
            queryVo.setId(roleId);
            //查询角色和权限(这里根据业务自行查询)
            List menuList = sysMenuService.selectPermsByRoleId(queryVo);
            List collect = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
            list.addAll(collect);
        }
        return list;
    }

    
    @Override
    public List getRoleList(Object loginId, String loginType) {
        List 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;

     
    @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);
            // StpUtil.login()可以设置登录的设备,比如web端登录,或者移动端登录,只需要设置device即可
            // StpUtil.login(user.getId(),"WEB");
            StpUtil.login(user.getId());
            
            String tokenValue = StpUtil.getTokenValue();

            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);
            }
            //将登录用户信息设置到session中
            StpUtil.getSession().set("user",user);
            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 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("退出登录成功");
    }

    
    @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 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;



public class RSAUtil {

    private static final KeyPair keyPair = initKey();

    
    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 static String getPublicKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // getEncoded():返回key的原始编码形式
        return new String(Base64.encodeBase64(publicKey.getEncoded()));
    }

    
    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;
    }

    
    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;

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

    
    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);
    }

    
    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;
    }

    
    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 登录拦截器修改

原:

 

修改:

//判断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);
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032455.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号