1 // ============LICENSE_START===============================================
2 // Copyright (C) 2023 Nordix Foundation. All rights reserved.
3 // ========================================================================
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 // ============LICENSE_END=================================================
18 package org.oran.pmlog.oauth2;
20 import com.fasterxml.jackson.core.JsonProcessingException;
21 import com.fasterxml.jackson.databind.JsonMappingException;
23 import java.util.Base64;
24 import java.util.HashSet;
27 import lombok.ToString;
29 import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken;
30 import org.oran.pmlog.exceptions.ServiceException;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
34 public class OAuthBearerTokenJwt implements OAuthBearerToken {
35 private static final Logger logger = LoggerFactory.getLogger(OAuthBearerTokenJwt.class);
36 private static final com.google.gson.Gson gson = new com.google.gson.GsonBuilder().disableHtmlEscaping().create();
38 private final String jwtTokenRaw;
39 private final JwtTokenBody tokenBody;
42 private static class JwtTokenBody {
43 String sub = ""; // principalName
44 long exp = 0; // expirationTime
45 long iat = 0; // startTime
49 public static OAuthBearerTokenJwt create(String tokenRaw)
50 throws ServiceException, JsonMappingException, JsonProcessingException {
51 String[] chunks = tokenRaw.split("\\.");
52 Base64.Decoder decoder = Base64.getUrlDecoder();
53 if (chunks.length < 2) {
54 throw new ServiceException("Could not parse JWT token: " + tokenRaw);
57 String payloadStr = new String(decoder.decode(chunks[1]));
58 JwtTokenBody token = gson.fromJson(payloadStr, JwtTokenBody.class);
59 logger.error("Token: {}", token);
60 return new OAuthBearerTokenJwt(token, tokenRaw);
63 private OAuthBearerTokenJwt(JwtTokenBody jwtTokenBody, String accessToken) {
65 this.jwtTokenRaw = accessToken;
66 this.tokenBody = jwtTokenBody;
70 public String value() {
75 public Set<String> scope() {
76 Set<String> res = new HashSet<>();
77 if (!this.tokenBody.scope.isEmpty()) {
78 res.add(this.tokenBody.scope);
84 public long lifetimeMs() {
85 if (this.tokenBody.exp == 0) {
86 return Long.MAX_VALUE;
88 return this.tokenBody.exp * 1000;
92 public String principalName() {
93 return this.tokenBody.sub;
97 public Long startTimeMs() {
98 return this.tokenBody.iat;