• SpringBoot--token校验登录


    生成token工具类

    package com.eccom.asset.utils;
    
    import com.auth0.jwt.JWT;
    import com.auth0.jwt.JWTVerifier;
    import com.auth0.jwt.algorithms.Algorithm;
    import com.auth0.jwt.exceptions.JWTDecodeException;
    import com.auth0.jwt.exceptions.JWTVerificationException;
    
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @author 一只小海猪
     * * @date 2022/8/4
     * Jwt工具类
     */
    public class JwtUtil {
        /**
         * 过期5分钟
         * */
        private static final long EXPIRE_TIME = 5 * 60 * 1000;
    
        /**
         * jwt密钥
         * */
        private static final String SECRET = "jwt_secret";
    
        /**
         * 生成jwt字符串,五分钟后过期  JWT(json web token)
         * @param userCode
         * @param info,Map的value只能存放值的类型为:Map,List,Boolean,Integer,Long,Double,String and Date
         * @return
         * */
        public static String sign(String userCode, Map<String, Object> info) {
            try {
                Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
                Algorithm algorithm = Algorithm.HMAC256(SECRET);
                String token = JWT.create()
                        //将userCode保存到token里面
                        .withAudience(userCode)
                        //存放自定义数据
                        .withClaim("info", info)
                        //五分钟后token过期
                        .withExpiresAt(date)
                        //token的密钥
                        .sign(algorithm);
                return token;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 根据token获取usercode
         * @param token
         * @return
         * */
        public static String getUserCode(String token) {
            try {
                String userCode = JWT.decode(token).getAudience().get(0);
                return userCode;
            }catch (JWTDecodeException e) {
                return null;
            }
        }
    
        /**
         * 根据token获取自定义数据info
         * @param token
         * @return
         * */
        public static Map<String, Object> getInfo(String token) {
            try {
                return JWT.decode(token).getClaim("info").asMap();
            }catch (JWTDecodeException e) {
                return null;
            }
        }
    
        /**
         * 校验token
         * @param token
         * @return
         * */
        public static boolean checkSign(String token) {
            try {
                Algorithm algorithm  = Algorithm.HMAC256(SECRET);
                JWTVerifier verifier = JWT.require(algorithm)
                        //.withClaim("username, username)
                        .build();
                verifier.verify(token);
                return true;
            }catch (JWTVerificationException e) {
                throw new RuntimeException("token 无效,请重新获取");
            }
        }
        /*
        测试token校验登录
         */
        public static void main(String[] args) {
            Map<String, Object> info = new HashMap<>();
            info.put("userCode","admin");
            info.put("password","123456");
            String token = sign("admin",info);
            System.out.println(token);
            System.out.println(getUserCode(token));
            System.out.println(getInfo(token));
            System.out.println(checkSign(token));
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113

    登录拦截器

    package com.eccom.asset.interceptor;
    
    import com.eccom.asset.utils.JwtUtil;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Map;
    
    /**
     * @author 一只小海猪
     * * @date 2022/8/4
     * Jwt登录拦截器
     */
    public class JwtInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //如果不是映射到方法直接通过
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
    
            //从 http 请求头中取出 token
            String token = request.getHeader("token");
            System.out.println("此处测试是否拿到了token:" + token);
    
            if (token == null) {
                throw new RuntimeException("无 token ,请重新登陆");
            }
    
            //验证 token
            JwtUtil.checkSign(token);
    
            //验证通过后, 这里测试取出JWT中存放的数据
            //获取 token 中的 userCode
            String userCode= JwtUtil.getUserCode(token);
            System.out.println("userCode: " + userCode);
    
            //获取 token 中的其他数据
            Map<String, Object> info = JwtUtil.getInfo(token);
            info.forEach((k, v) -> System.out.println(k + ":" + v));
            return true;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    MVC配置类

    package com.eccom.asset.config;
    
    import com.eccom.asset.interceptor.JwtInterceptor;
    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;
    
    /**
     * @author 一只小海猪
     * * @date 2022/8/4
     */
    
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
        /**
         * 添加jwt拦截器,并指定拦截路径
         * */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(jwtInterceptor()).addPathPatterns("/login/**");
        }
    
        /**
         * jwt拦截器
         * */
        @Bean
        public JwtInterceptor jwtInterceptor() {
            return new JwtInterceptor();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    经过这么拦截之后,登录路径就会进行拦截,对用户密码,账号,token进行验证,之后整个项目都需要对用户进行验证,通过后才可以访问后面资源。

    token依赖

            <!--token验证-->
            <!-- 引入操作JWT的相关依赖 -->
            <dependency>
                <groupId>com.auth0</groupId>
                <artifactId>java-jwt</artifactId>
                <version>4.0.0</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    android中输入系统之内核到InputManagerService过程(源码)
    基于MYSQL的新闻发布系统数据库设计项目实战
    15. Python 赋值运算
    从硬件到软件:揭秘磁盘结构和文件系统组织
    目录和文件管理
    前端性能优化概述
    加强堆结构说明
    2023 年 QQ 小程序企业资质开通 QQ 支付、微信支付轻量级后台搭建(详细教程)
    [StartingPoint][Tier1]Crocodile
    SSM+老年人活动信息管理系统 毕业设计-附源码121730
  • 原文地址:https://blog.csdn.net/qq_43804919/article/details/126463007