spring boot整合JWT

  • 引入项目依赖

            
                io.jsonwebtoken
                jjwt-api
                0.11.2
            
            
                io.jsonwebtoken
                jjwt-impl
                0.11.2
                runtime
            
            
                io.jsonwebtoken
                jjwt-jackson 
                0.11.2
                runtime
            

  • 编写JWT工具类

    public class JWTUtils {
        private static final String APP_SECRET = "JDSAdGdFjJjJhGfgVvhuiUhHhJJKkHJHJhkjkHJKJKjkHJ";
        public static String getToken(Map map){
            JwtBuilder builder = Jwts.builder();
    //这里可以实现外部动态传参
            map.forEach((k,v)->{
                builder.claim(k,v);
                    }
            );
            String token = builder
    //token开始起作用的时间
                    .setIssuedAt(new Date())
    //token失效时间
                    .setExpiration(new Date(System.currentTimeMillis()+1000*60*5))
                    .signWith(Keys.hmacShaKeyFor(APP_SECRET.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256)
                    .compact();
            System.out.println("token:"+token);
            return token;
        }
        public static void verify(String token){
             Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(APP_SECRET.getBytes(StandardCharsets.UTF_8)))
                    .build()
                    .parseClaimsJws(token);
        }
        public static Jws  tokenInfo(String token){
            Jws claimsJws = Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(APP_SECRET.getBytes(StandardCharsets.UTF_8)))
                    .build()
                    .parseClaimsJws(token);
            return claimsJws;
        }
    }

  • 在登录controler中使用工具类

    @Autowired
        UserService userService;
        @PostMapping("/user/login")
        public Map Login(User user){
    //这里只是起测试作用
    //      log.info(user.getName());
    //      log.info(user.getPassword());
            Map map = new HashMap<>();
            try {
                User UserDat = userService.login(user);
                Map payload = new HashMap<>();
                payload.put("id",Integer.toString(UserDat.getId()));
                payload.put("name",UserDat.getName());
                String token = JWTUtils.getToken(payload);
                map.put("state",200);
                map.put("message","登录成功");
                map.put("token",token);
    
            }catch (Exception e){
                map.put("state",400);
                map.put("message","登陆失败");
            }
            return map;
        }

  • 优化:拦截器,拦截除了用户界面的其他界面

         拦截器:

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map map = new HashMap<>();
        String token = request.getHeader("token");
        try {
            // 1.校验JWT字符串
            JWTUtils.verify(token);
            // 2.取出JWT字符串载荷中的随机token,从Redis中获取用户信息
            map.put("state",200);
            map.put("msg","token验证成功");
            return true;
        } catch (ExpiredJwtException e){
            e.printStackTrace();
            map.put("msg","token已过期");
        }catch (MalformedJwtException e){
//            System.out.println("算法不一致");
            e.printStackTrace();
            map.put("msg","算法不一致");
        }catch (Exception e){
//            System.out.println("token无效");
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("state",400);
//将map转换成json对象返回
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

   拦截器的配置类:

@Configuration
public class interceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JwtInterceptor())
//拦截的页面
                .addPathPatterns("/token/test")
//被排除拦截的页面
                .excludePathPatterns("/user/login");
    }
}
  •  总结:

           这是我在刚学习jwt时所写的一些代码以及经验,可能有些地方存在问题还望大家给出建议。这只是一些入门的内容,大家可以借鉴学习一下。

你可能感兴趣的:(JWT,java,spring,maven,java-ee,intellij,idea)