| | |
| | | |
| | | import com.auth0.jwt.JWT; |
| | | import com.auth0.jwt.algorithms.Algorithm; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * OnlyOffice JWT令牌生成工具类 |
| | | * <p> |
| | | * 用于生成OnlyOffice Document Server所需的JWT令牌, |
| | | * 密钥通过Nacos配置中心统一管理。 |
| | | * </p> |
| | | * |
| | | * @author sxkj |
| | | */ |
| | | @Slf4j |
| | | @Component |
| | | public class OnlyofficeJwt { |
| | | |
| | | /** |
| | | * 把jsonObject返回给前端使用 |
| | | * @return ztzf-wv5d0-kx5xo-dx2w2-xpx5q |
| | | * JWT令牌签名密钥,从Nacos配置读取 |
| | | */ |
| | | public static Map<String, Object> getToken(Map<String, Object> config){ |
| | | // String tokenSecret = "ztzf-aisky-kx5xo-dx2w2-xpx5q"; |
| | | String tokenSecret = "ztzf-wv5d0-kx5xo-dx2w2-xpx5q"; |
| | | String token = ""; |
| | | @Value("${onlyoffice.token-secret:ztzf-aisky-kx5xo-dx2w2-xpx5q}") |
| | | private String tokenSecret; |
| | | |
| | | /** |
| | | * 生成JWT令牌并将令牌添加到配置Map中 |
| | | * <p> |
| | | * 使用HMAC256算法对OnlyOffice配置进行签名, |
| | | * 生成令牌后将其放入config的token字段。 |
| | | * </p> |
| | | * |
| | | * @param config OnlyOffice编辑器配置Map,包含document、editorConfig等信息 |
| | | * @return 添加了token字段的配置Map |
| | | */ |
| | | public Map<String, Object> getToken(Map<String, Object> config) { |
| | | String token = ""; |
| | | try { |
| | | // Signer signer = HMACSigner.newSHA256Signer(tokenSecret); |
| | | // JWT jwt = new JWT(); |
| | | // for (String key : payloadClaims.keySet()) { |
| | | // jwt.addClaim(key, payloadClaims.get(key)); |
| | | // } |
| | | // token = JWT.getEncoder().encode(jwt, signer); |
| | | |
| | | // 1. 使用配置的密钥创建HMAC256签名算法 |
| | | Algorithm algorithm = Algorithm.HMAC256(tokenSecret); |
| | | // Calendar calendar = Calendar.getInstance(); |
| | | // Instant issuedAt = calendar.toInstant(); |
| | | // calendar.add(12, 5); |
| | | // Instant expiresAt = calendar.toInstant(); |
| | | // token = JWT.create().withIssuedAt(issuedAt).withExpiresAt(expiresAt).withPayload(payloadClaims).sign(algorithm); |
| | | |
| | | token = JWT.create() |
| | | // 2. 基于config负载生成JWT令牌 |
| | | token = JWT.create() |
| | | .withPayload(config) |
| | | .sign(algorithm); |
| | | } catch (Exception e) { |
| | | log.error("生成OnlyOffice JWT令牌失败: {}", e.getMessage(), e); |
| | | token = ""; |
| | | } |
| | | |
| | | // 3. 将生成的令牌放入配置中 |
| | | config.put("token", token); |
| | | return config; |
| | | } |