import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())//拦截器自定义拦截逻辑执行类
                .addPathPatterns("/**")//拦截所有请求地址
                .excludePathPatterns("/data-admin/*/login");//越过拦截所有请求,通过判断token是否合法来决定是否需要登录
    }

    @Bean
    public JwtInterceptor jwtInterceptor(){
        return new JwtInterceptor();
    }
}

执行类:

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //执行认证
        if (StrUtil.isBlank(token)) {

            throw new ServiceException("无token,请重新登录");

        }
//        //获取token中的username
//        String userName;
//        try {
//            userName = JWT.decode(token).getAudience().get(0);
//
//        } catch (JWTDecodeException j) {
//            throw new RuntimeException("token异常");
//        }
//        //查看token的username
//        if (!userName.equals("admin")) {
//            throw new ServiceException("用户不存在");
//        }
//        //密码加签验证token
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build();
//        try {
//            jwtVerifier.verify(token);
//        } catch (JWTVerificationException e) {
//            throw new ServiceException("token验证失败,请重新登录");
//        }

        String name = "admin";
        String password = "";
        try {
            //获取redis中的密码
            password = String.valueOf(redisTemplate.opsForValue().get("admin"));
        } catch (Exception e) {
            throw new ServiceException("redis连接失败,请联系管理员");
        }
        //验证token加密串
        try {
            if (!MD5Util.verify(name + password, token)) {
                throw new ServiceException("token验证失败,请重新登录");
            }
        } catch (JWTVerificationException e) {
            throw new ServiceException("token验证失败,请重新登录");
        }
        return true;
    }
}

 

 

redis连接工具类:

@Configuration
public class RedisConfig {
    @Bean(name="redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(redisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(redisSerializer);
        //key haspmap序列化
        template.setHashKeySerializer(redisSerializer);
        return template;
    }
}

 

简单的MD5加解密,签名认证:

public class MD5Util {

    //秘钥
    public static final String KEY = "***********";

    /**
     * 带秘钥加密
     *
     * @param text 明文
     * @return 密文
     */
    public static String md5(String text) {
        // 加密后的字符串
        String md5str = DigestUtils.md5Hex(text + KEY);
        System.out.println("MD5加密后的字符串为:" + md5str);
        return md5str;
    }

    /**
     * MD5验证方法 根据传入的密钥进行验证
     *
     * @param text 明文
     * @param md5  密文
     * @return
     * @throws Exception
     */
    public static boolean verify(String text, String md5) {
        String md5str = md5(text);
        if (md5str.equalsIgnoreCase(md5)) {
            System.out.println("MD5验证通过");
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String signKeyMd5 = md5("明文");
        System.out.println(signKeyMd5);
        System.out.println(verify("admin", signKeyMd5));
    }

 

posted on 2022-09-08 17:04  茫无所知  阅读(13)  评论(0编辑  收藏  举报