一:导入配置文件
<!-- JWT--> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </dependency>
二:可以先在ApplicationTests中测试看一些效果
package com.zsbb.jwt; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import com.zsbb.jwt.Service.UserService; import com.zsbb.jwt.entity.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Calendar; import java.util.HashMap; @SpringBootTest class JwtApplicationTests { @Test void contextLoads() { HashMap<String,Object> map=new HashMap<>(); //日历类 Calendar instance=Calendar.getInstance(); //二十秒后过期 instance.add(Calendar.SECOND,2000); String token=JWT.create() .withHeader(map) // 可以放多个参数 .withClaim("id",12) .withClaim("username","老王") .withExpiresAt(instance.getTime()) //令牌过期时间 // 密钥:zsbb .sign(Algorithm.HMAC256("zsbb")); //签名 System.out.println(token); } @Test public void test(){ //创建验证对象 JWTVerifier jwtVerifier= JWT.require(Algorithm.HMAC256("zsbb")).build(); //验证token DecodedJWT verify = jwtVerifier.verify ("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTIsImV4cCI6MTY2Nzg2ODcxMSwidXNlcm5hbWUiOiLogIHnjosifQ.qBcsUHnQWJE0ljTGZ9IDFTh6c0xIv5mh0e5KgejiL5c\n"); System.out.println(verify); //单个参数取 System.out.println(verify.getClaim("username").asString()); //多个参数取 System.out.println(verify.getClaims().get("username").asString()); System.out.println(verify.getClaims().get("id").asInt()); }
效果图:
1:得到token
2:校验token
三:与SpringBoot集成首先封装utils
package com.zsbb.jwt.utis; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.Calendar; import java.util.Map; public class JWTUtis { private static String SING="zsbb"; /* * 生成token * */ public static String getToken(Map<String,String> map){ Calendar instance=Calendar.getInstance(); //十天后过期 instance.add(Calendar.SECOND,10); //创建Builder JWTCreator.Builder builder=JWT.create(); map.forEach((k,v)->{ builder.withClaim(k,v); }); String token= builder.withExpiresAt(instance.getTime()) .sign(Algorithm.HMAC256(SING)); return token; } /* * 验证token合法性 * */ public static DecodedJWT verify(String token){ return JWT.require(Algorithm.HMAC256(SING)).build().verify(token); } // /* // * 获取token信息 // * */ // public static DecodedJWT getTokenInfo(String token){ // DecodedJWT verify=JWT.require(Algorithm.HMAC256(SING)).build().verify(token); // return verify; // } }
四:编写Entity、Service、Serviceimpl、Mapper、Controller
Entity
package com.zsbb.jwt.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class User { private int id; private String name; private String password; }
Service
package com.zsbb.jwt.Service; import com.zsbb.jwt.entity.User; import java.util.List; public interface UserService { User login(User user); }
Serviceimpl
package com.zsbb.jwt.Service.impl; import com.zsbb.jwt.Service.UserService; import com.zsbb.jwt.entity.User; import com.zsbb.jwt.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceimpl implements UserService { @Autowired UserMapper userMapper; @Override public User login(User user) { return userMapper.login(user); } }
Controller
package com.zsbb.jwt.controller; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.DecodedJWT; import com.zsbb.jwt.Service.UserService; import com.zsbb.jwt.entity.User; import com.zsbb.jwt.utis.JWTUtis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/login") public class UserController { @Autowired UserService userService; @PostMapping("/JWTlogin") public Map<String,Object> Login(@RequestBody User user){ Map<String,Object> map=new HashMap<>(); try { User userDB=userService.login(user); Map<String,String> payload=new HashMap<>(); payload.put("id",String.valueOf(userDB.getId())); payload.put("name",userDB.getName()); //生成JWT的令牌 String token=JWTUtis.getToken(payload); map.put("state",true); map.put("msg","认证成功"); //抛出token map.put("token",token); }catch (Exception e){ map.put("state",false); map.put("msg",e.getMessage()); } return map; } @PostMapping("/text") public Map<String,Object> test(@RequestParam(required = true, defaultValue = "0") String token){ Map<String,Object> map=new HashMap<>(); //处理自己业务逻辑 map.put("state",true); map.put("msg","请求成功!"); return map; } }
五:封装异常处理,添加拦截器
异常处理
package com.zsbb.jwt.interceptor; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.fasterxml.jackson.databind.ObjectMapper; import com.zsbb.jwt.utis.JWTUtis; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; public class JWTInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token=request.getHeader("token"); Map<String,Object> map=new HashMap<>(); try { JWTUtis.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("state",false);//设置状态 //将map转json String json=new ObjectMapper().writeValueAsString(map); response.setContentType("application/json;charset=UTF-8"); response.getWriter().println(json); return false; } }
拦截器
package com.zsbb.jwt.config; import com.zsbb.jwt.interceptor.JWTInterceptor; 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(new JWTInterceptor()) //拦截的请求 .addPathPatterns("/**") //所有的接口都要token验证 //放行请求 .excludePathPatterns("/login/JWTlogin"); //所以用户的登录操作都放行 } }
六:效果图
校验token:
完结撒花!!!
标签:map,jwt,JWT,token,zsbb,import,自学,com From: https://www.cnblogs.com/zsbb/p/16868470.html