• SpringBoot整合JWT


    JWT

    (整合SpringBoot)

    1. 引入依赖

    <!--    引入JWT    -->
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.4.0</version>
    </dependency>
    

    2. 编写工具类

    public class JWTUtil {
    
        // 用于JWT进行签名加密的秘钥
        private static String SECRET = "code-duck-*%#@*!&";
    
        /**
         * @Param: 传入需要设置的payload信息
         * @return: 返回token
         */
        public static String generateToken(Map<String, String> map) {
            JWTCreator.Builder builder = JWT.create();
    
            // 将map内的信息传入JWT的payload中
            map.forEach((k, v) -> {
                builder.withClaim(k, v);
            });
    
            // 设置JWT令牌的过期时间为60
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.SECOND, 60);
            builder.withExpiresAt(instance.getTime());
    
            // 设置签名并返回token
            return builder.sign(Algorithm.HMAC256(SECRET)).toString();
        }
    
        /**
         * @Param: 传入token
         * @return:
         */
        public static void verify(String token) {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }
    
        /**
         * @Param: 传入token
         * @return: 解密的token信息
         */
        public static DecodedJWT getTokenInfo(String token) {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }
    }
    

    3. 准备项目测试环境

    编写controller>service>mapper

    4. 获取Token

    UserController.java

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @PostMapping("/login")
        public Map<String,String> login(@RequestParam("username")String username,
                                        @RequestParam("password")String password){
    
            HashMap<String, String> result = new HashMap<>();
    
            User user = userService.getUser(username);
    
            //返回用户为空,则说明此用户名信息不存在
            if (user==null){
                result.put("msg", "用户不存在");
                return result;
            }
    
            //判断密码是否正确
            if (!user.getPassword().equals(password)){
                result.put("msg", "密码错误");
                return result;
            }
    
            //验证通过
            HashMap<String, String> map = new HashMap<>();
            map.put("msg","success");
            map.put("username",username);
            map.put("role","admin");
    
            //生成token
            String token = JwtUtils.generateToken(map);
    
            result.put("token", token);
    
            return result;
        }
    
        @RequestMapping("/test")
        public String test(){
    
            return "请求成功!!!";
        }
    }
    

    5. 编写拦截器

    JwtInceptor.java

    public class JwtInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String token = request.getHeader("token");
            HashMap<String, String> map = new HashMap<>();
            try {
                JwtUtils.verify(token);//验证令牌
                return true;//放行请求
            } catch (SignatureVerificationException e) {
                e.printStackTrace();
                map.put("msg", "无效签名!");
            } catch (TokenExpiredException e) {
                e.printStackTrace();
                map.put("msg", "token过期!");
            } catch (AlgorithmMismatchException e) {
                e.printStackTrace();
                map.put("msg", "token算法不一致!");
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg", "token无效!!");
            }
            map.put("code", "403");//设置状态
            //将 map 转为json  jackson
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json); //前台返回数据
            return false;
        }
    }
    

    6. 注册MVC配置

    JwtInterceptorConfig.java

    @Configuration
    public class JwtInterceptorConfig implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new JwtInterceptor()) //注册自定义拦截器
                    .addPathPatterns("/**") //拦截所有路径
                    .excludePathPatterns("/user/login"); //排除登陆请求
        }
    }
    
  • 相关阅读:
    ios 分享腾讯微博
    ios 分享微信
    elinput 价格校验 大于0保留2位小数,不包含01,01.1这种
    从范闲到许乐,从宁缺再到陈长生
    二进制流 ajax 实现图片上传
    php 操作redis 部分命令
    matlab 与vs2008联合编程的设置备忘
    新型机器人闯入职场:到底是工作缔造者还是工作终结者?
    c++ vs2008 多线程编程的样例
    虚拟试衣创业公司Fitiquette被印度电商Myntra收购
  • 原文地址:https://www.cnblogs.com/shmebluk/p/14093055.html
Copyright © 2020-2023  润新知