2 * ========================LICENSE_START=================================
4 * Copyright (C) 2023 Nordix Foundation
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ========================LICENSE_END===================================
20 package org.oran.pmlog.oauth2;
22 import java.util.Base64;
23 import java.util.HashSet;
25 import lombok.ToString;
26 import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken;
27 import org.oran.pmlog.exceptions.ServiceException;
29 public class OAuthBearerTokenJwt implements OAuthBearerToken {
30 private static final com.google.gson.Gson gson = new com.google.gson.GsonBuilder().disableHtmlEscaping().create();
32 private final String jwtTokenRaw;
33 private final JwtTokenBody tokenBody;
36 private static class JwtTokenBody {
37 String sub = ""; // principalName
38 long exp = 0; // expirationTime
39 long iat = 0; // startTime
43 public static OAuthBearerTokenJwt create(String tokenRaw)
44 throws ServiceException {
45 String[] chunks = tokenRaw.split("\\.");
46 Base64.Decoder decoder = Base64.getUrlDecoder();
47 if (chunks.length < 2) {
48 throw new ServiceException("Could not parse JWT token: " + tokenRaw);
51 String payloadStr = new String(decoder.decode(chunks[1]));
52 JwtTokenBody token = gson.fromJson(payloadStr, JwtTokenBody.class);
53 return new OAuthBearerTokenJwt(token, tokenRaw);
56 private OAuthBearerTokenJwt(JwtTokenBody jwtTokenBody, String accessToken) {
58 this.jwtTokenRaw = accessToken;
59 this.tokenBody = jwtTokenBody;
63 public String value() {
68 public Set<String> scope() {
69 Set<String> res = new HashSet<>();
70 if (!this.tokenBody.scope.isEmpty()) {
71 res.add(this.tokenBody.scope);
77 public long lifetimeMs() {
78 if (this.tokenBody.exp == 0) {
79 return Long.MAX_VALUE;
81 return this.tokenBody.exp * 1000;
85 public String principalName() {
86 return this.tokenBody.sub;
90 public Long startTimeMs() {
91 return this.tokenBody.iat;