1.引入pom文件

    1. <dependency>
    2. <groupId>com.auth0</groupId>
    3. <artifactId>java-jwt</artifactId>
    4. <version>3.8.1</version>
    5. </dependency>

    2.创建Token的DTO

    1. @Getter
    2. @Setter
    3. public class TokenGetDTO {
    4. @NotBlank(message = "account不允许为空")
    5. private String account;
    6. @TokenPassword(max=30, message = "{token.password}")
    7. private String password;
    8. private LoginType Type;
    9. }

    3.在Service层创建WxAuthenticationService

    1. @Service
    2. public class WxAuthenticationService {
    3. @Autowired(required = false)
    4. private ObjectMapper mapper;
    5. @Autowired(required = false)
    6. private UserRepository userRepository;
    7. @Value("${wx.code2session}")
    8. private String code2SessionUrl;
    9. @Value("{$wx.appid}")
    10. private String appid;
    11. @Value("{$wx.appsecret}")
    12. private String appsecret;
    13. public String code2Session(String code){
    14. //进行字符串的拼接
    15. String url = MessageFormat.format(this.code2SessionUrl,this.appid,this.appsecret);
    16. /*RestTemplate可以进行请求发送*/
    17. RestTemplate rest = new RestTemplate();
    18. String sessionText = rest.getForObject(url,String.class);
    19. /*反序列化*/
    20. Map<String, Object> session = new HashMap<>();
    21. try {
    22. session = mapper.readValue(sessionText,Map.class);
    23. } catch (JsonProcessingException e) {
    24. e.printStackTrace();
    25. }
    26. //调用registerUser方法来返回JWT令牌
    27. return this.registerUser(session);
    28. }
    29. private String registerUser(Map<String, Object> session){
    30. String openid = (String) session.get("openid");
    31. if (openid == null){
    32. throw new ParameterException(20004);
    33. }
    34. Optional<User> userOptional = this.userRepository.findByOpenid(openid);
    35. if (userOptional.isPresent()){
    36. //TODO:返回JWT令牌
    37. return JwtToken.makeToken(userOptional.get().getId());
    38. }
    39. User user = User.builder()
    40. .openid(openid)
    41. .build();
    42. userRepository.save(user);
    43. Long uid = user.getId();
    44. return JwtToken.makeToken(uid);
    45. }
    46. }

    4.在util包下创建JwtToken并编写getToken方法

    1. private static String getToken(long uid,Integer scope){
    2. // 调用Auth0的方法Algorithm.HMAC256
    3. Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey);
    4. //调用自定义的方法calculateExpiredIssues来计算时间
    5. Map<String, Date> map = calculateExpiredIssues();
    6. return JWT.create()
    7. .withClaim("uid",uid)
    8. .withClaim("scope",scope)
    9. .withExpiresAt(map.get("expiredTime"))
    10. .withIssuedAt(map.get("now"))
    11. .sign(algorithm);
    12. }
    13. private static Map<String, Date> calculateExpiredIssues() {
    14. Map<String, Date> map = new HashMap<>();
    15. Calendar calendar = Calendar.getInstance();
    16. Date now = calendar.getTime();
    17. calendar.add(Calendar.SECOND, JwtToken.expiredTimeIn);
    18. map.put("now", now);
    19. map.put("expiredTime", calendar.getTime());
    20. return map;
    21. }

    5.在makeToken方法中调用getToken来使用

    1. public static String makeToken(long uid){
    2. return JwtToken.getToken(uid, JwtToken.defaultScope);
    3. }

    6.在TokenController控制器中调用

    1. @RequestMapping(value = "token")
    2. @RestController
    3. public class TokenController {
    4. @Autowired
    5. private WxAuthenticationService wxAuthenticationService;
    6. @PostMapping("")
    7. public Map<String, String> getToken(@RequestBody @Validated TokenGetDTO userData) {
    8. Map<String, String> map = new HashMap<>();
    9. String token = null;
    10. switch (userData.getType()) {
    11. case USER_WX:
    12. token = wxAuthenticationService.code2Session(userData.getAccount());
    13. break;
    14. case USER_Email:
    15. break;
    16. default:
    17. throw new NotFoundException(10003);
    18. }
    19. map.put("token", token);
    20. return map;
    21. }
    22. @PostMapping("/verify")
    23. public Map<String, Boolean> verify(@RequestBody TokenDTO token) {
    24. Map<String, Boolean> map = new HashMap<>();
    25. Boolean valid = JwtToken.verifyToken(token.getToken());
    26. map.put("is_valid", valid);
    27. return map;
    28. }
    29. }