jwt

gsluofu發表於2024-09-01
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /* MethodHandle methodHandle = handler instanceof MethodHandle ? ((MethodHandle) handler) : null;
        if(methodHandle == null){
              return true;
        }*/
        String token = request.getHeader("token");

        DecodedJWT decode = JWT.decode(token);
        Claim name = decode.getClaim("name");
        System.out.println("TokenInterceptor name:"+name.as(String.class));

        boolean abc = JwtUtil.verify(token, "abc");
        System.out.println("TokenInterceptor abc:"+abc);
        return abc;
    }
}
 //implements WebMvcConfigurer 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePath = new ArrayList<>();
        excludePath.add("/channel/login");
        //登入
        registry.addInterceptor(tokenInterceptor)
                .excludePathPatterns(excludePath)
                .addPathPatterns("/**");
        //除了登陸介面其他所有介面都需要token驗證
        WebMvcConfigurer.super.addInterceptors(registry);

    }
public class JwtUtil {
    
    public static String getToken(User user){
        Map header = new HashMap<>();
        header.put("Content-Type","application/json");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,60);
        String token = JWT.create()
                .withHeader(header)
                .withClaim("name", user.getName())
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(user.getPass()));
        System.out.println("JwtUtil getToken token:"+token);
        return token;
    }
    
    public static boolean verify(String token,String pass){
        try {

            JWTVerifier require = JWT.require(Algorithm.HMAC256(pass)).build();
            DecodedJWT verify = require.verify(token);
            System.out.println("JwtUtil verify verify:"+verify);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
@ResponseBody
    @RequestMapping("/login")
    public String login(@RequestBody User user){
        //預設使用者登入成功
        //生成token
        String token = JwtUtil.getToken(user);
        user.setToken(token);
        return token;
    }