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.datafile.oauth2;
20 import java.util.Base64;
21 import java.util.HashSet;
24 import lombok.ToString;
26 import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken;
27 import org.oran.datafile.exceptions.DatafileTaskException;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 public class OAuthBearerTokenJwt implements OAuthBearerToken {
32 private static final Logger logger = LoggerFactory.getLogger(OAuthBearerTokenJwt.class);
33 private static final com.google.gson.Gson gson = new com.google.gson.GsonBuilder().disableHtmlEscaping().create();
35 private final String jwtTokenRaw;
36 private final JwtTokenBody tokenBody;
39 private static class JwtTokenBody {
40 String sub = ""; // principalName
41 long exp = 0; // expirationTime
42 long iat = 0; // startTime
46 public static OAuthBearerTokenJwt create(String tokenRaw) throws DatafileTaskException {
47 String[] chunks = tokenRaw.split("\\.");
48 Base64.Decoder decoder = Base64.getUrlDecoder();
49 if (chunks.length < 2) {
50 throw new DatafileTaskException("Could not parse JWT token: " + tokenRaw);
53 String payloadStr = new String(decoder.decode(chunks[1]));
54 JwtTokenBody token = gson.fromJson(payloadStr, JwtTokenBody.class);
55 logger.debug("Token: {}", token);
56 return new OAuthBearerTokenJwt(token, tokenRaw);
59 private OAuthBearerTokenJwt(JwtTokenBody jwtTokenBody, String accessToken) {
61 this.jwtTokenRaw = accessToken;
62 this.tokenBody = jwtTokenBody;
66 public String value() {
71 public Set<String> scope() {
72 Set<String> res = new HashSet<>();
73 if (!this.tokenBody.scope.isEmpty()) {
74 res.add(this.tokenBody.scope);
80 public long lifetimeMs() {
81 if (this.tokenBody.exp == 0) {
82 return Long.MAX_VALUE;
84 return this.tokenBody.exp * 1000;
88 public String principalName() {
89 return this.tokenBody.sub;
93 public Long startTimeMs() {
94 return this.tokenBody.iat;