1.引入pom文件
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.1</version>
</dependency>
2.创建Token的DTO
@Getter
@Setter
public class TokenGetDTO {
@NotBlank(message = "account不允许为空")
private String account;
@TokenPassword(max=30, message = "{token.password}")
private String password;
private LoginType Type;
}
3.在Service层创建WxAuthenticationService
@Service
public class WxAuthenticationService {
@Autowired(required = false)
private ObjectMapper mapper;
@Autowired(required = false)
private UserRepository userRepository;
@Value("${wx.code2session}")
private String code2SessionUrl;
@Value("{$wx.appid}")
private String appid;
@Value("{$wx.appsecret}")
private String appsecret;
public String code2Session(String code){
//进行字符串的拼接
String url = MessageFormat.format(this.code2SessionUrl,this.appid,this.appsecret);
/*RestTemplate可以进行请求发送*/
RestTemplate rest = new RestTemplate();
String sessionText = rest.getForObject(url,String.class);
/*反序列化*/
Map<String, Object> session = new HashMap<>();
try {
session = mapper.readValue(sessionText,Map.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//调用registerUser方法来返回JWT令牌
return this.registerUser(session);
}
private String registerUser(Map<String, Object> session){
String openid = (String) session.get("openid");
if (openid == null){
throw new ParameterException(20004);
}
Optional<User> userOptional = this.userRepository.findByOpenid(openid);
if (userOptional.isPresent()){
//TODO:返回JWT令牌
return JwtToken.makeToken(userOptional.get().getId());
}
User user = User.builder()
.openid(openid)
.build();
userRepository.save(user);
Long uid = user.getId();
return JwtToken.makeToken(uid);
}
}
4.在util包下创建JwtToken并编写getToken方法
private static String getToken(long uid,Integer scope){
// 调用Auth0的方法Algorithm.HMAC256
Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey);
//调用自定义的方法calculateExpiredIssues来计算时间
Map<String, Date> map = calculateExpiredIssues();
return JWT.create()
.withClaim("uid",uid)
.withClaim("scope",scope)
.withExpiresAt(map.get("expiredTime"))
.withIssuedAt(map.get("now"))
.sign(algorithm);
}
private static Map<String, Date> calculateExpiredIssues() {
Map<String, Date> map = new HashMap<>();
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
calendar.add(Calendar.SECOND, JwtToken.expiredTimeIn);
map.put("now", now);
map.put("expiredTime", calendar.getTime());
return map;
}
5.在makeToken方法中调用getToken来使用
public static String makeToken(long uid){
return JwtToken.getToken(uid, JwtToken.defaultScope);
}
6.在TokenController控制器中调用
@RequestMapping(value = "token")
@RestController
public class TokenController {
@Autowired
private WxAuthenticationService wxAuthenticationService;
@PostMapping("")
public Map<String, String> getToken(@RequestBody @Validated TokenGetDTO userData) {
Map<String, String> map = new HashMap<>();
String token = null;
switch (userData.getType()) {
case USER_WX:
token = wxAuthenticationService.code2Session(userData.getAccount());
break;
case USER_Email:
break;
default:
throw new NotFoundException(10003);
}
map.put("token", token);
return map;
}
@PostMapping("/verify")
public Map<String, Boolean> verify(@RequestBody TokenDTO token) {
Map<String, Boolean> map = new HashMap<>();
Boolean valid = JwtToken.verifyToken(token.getToken());
map.put("is_valid", valid);
return map;
}
}