AccessClient.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package com.miniframe.service;
  2. import com.miniframe.tools.JwtManageUtil;
  3. import java.util.Date;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class AccessClient {
  7. public static Map<String,AccessToken> clientJwtToken=new HashMap<>();
  8. public static class AccessToken{
  9. private String uniqueId;
  10. private String token;
  11. private String userId;
  12. private String saltToken;
  13. private Date lastTokenTime;
  14. public String getUniqueId() {
  15. return uniqueId;
  16. }
  17. public void setUniqueId(String uniqueId) {
  18. this.uniqueId = uniqueId;
  19. }
  20. public String getUserId() {
  21. return userId;
  22. }
  23. public void setUserId(String userId) {
  24. this.userId = userId;
  25. }
  26. public String getSaltToken() {
  27. return saltToken;
  28. }
  29. public void setSaltToken(String saltToken) {
  30. this.saltToken = saltToken;
  31. }
  32. public Date getLastTokenTime() {
  33. return lastTokenTime;
  34. }
  35. public AccessToken(String uniqueId, String userId, String saltToken){
  36. this.uniqueId=uniqueId;
  37. this.userId=userId;
  38. this.saltToken=saltToken;
  39. generateToken();
  40. }
  41. private void generateToken(){
  42. try {
  43. this.lastTokenTime=new Date();
  44. this.token=JwtManageUtil.getClientJWT(uniqueId,userId,saltToken);
  45. } catch (Exception e) {
  46. this.token=null;
  47. this.lastTokenTime=null;
  48. e.printStackTrace();
  49. }
  50. }
  51. public String getToken(){
  52. if(lastTokenTime==null){
  53. generateToken();
  54. }else{
  55. Date now=new Date();
  56. if((now.getTime()+600000-lastTokenTime.getTime())>=JwtManageUtil.Constant.JWT_TTL){ //token超时,重新生成
  57. generateToken();
  58. }
  59. }
  60. return this.token;
  61. }
  62. }
  63. static {
  64. try {
  65. //增加jwt token :projectName svcName userToAccessSvc
  66. clientJwtToken.put("cae_service_manager",new AccessToken("b87cb209-e852-42bc-8d58-bc771a57b3eb","manager","12345678901234567890"));
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. public static String getToken(String projectName,String serviceName,String user){
  72. String id=projectName+"_"+serviceName+"_"+user;
  73. if(clientJwtToken.containsKey(id)){
  74. return clientJwtToken.get(id).getToken();
  75. }
  76. return "";
  77. }
  78. }