bee29c83928d42b16fdfd99dc8e8e90d90718281
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2025 OpenInfra Foundation Europe. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21  package org.onap.ccsdk.oran.a1policymanagementservice.service.v3;
22
23  import java.lang.invoke.MethodHandles;
24  import java.util.Base64;
25
26  import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfo;
27  import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
28  import org.slf4j.Logger;
29  import org.slf4j.LoggerFactory;
30  import org.springframework.http.HttpHeaders;
31  import org.springframework.stereotype.Service;
32  import org.springframework.web.server.ServerWebExchange;
33
34  import com.google.gson.JsonObject;
35  import com.google.gson.JsonParser;
36
37  @Service
38  public class TokenService {
39      private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
40
41      // Prefix used to identify Bearer tokens in the Authorization header
42      private static final String BEARER_PREFIX = "Bearer ";
43
44
45      /**
46       * Retrieves the service ID for version 3 (v3) of the API, which uses PolicyObjectInformation.
47       *
48       * @param policyInfoValue The PolicyObjectInformation object containing the policy details.
49       * @param exchange The ServerWebExchange object that contains request and response information.
50       * @return The service ID, either from the policy information or derived from the client ID in the token.
51       */
52      public String getServiceId(PolicyObjectInformation policyInfoValue, ServerWebExchange exchange) {
53          String serviceId = policyInfoValue.getServiceId();
54          String clientId = extractClientIdFromToken(exchange);
55
56          // If the service ID from the policy is blank, use the client ID from the token instead
57          if (serviceId.isBlank()) {
58              if (clientId != null && !clientId.isBlank()) {
59                  serviceId = clientId;
60              }
61          }
62          // Return the determined service ID
63          logger.debug("ServiceID extracted from token: "  + serviceId);
64          return serviceId;
65      }
66
67      /**
68       * Retrieves the service ID for version 2 (v2) of the API, which uses PolicyInfo.
69       *
70       * @param policyInfoValue The PolicyInfo object containing the policy details.
71       * @param exchange The ServerWebExchange object that contains request and response information.
72       * @return The service ID, either from the policy information or derived from the client ID in the token.
73       */
74      public String getServiceId(PolicyInfo policyInfoValue, ServerWebExchange exchange) {
75          String serviceId = policyInfoValue.getServiceId();
76          String clientId = extractClientIdFromToken(exchange);
77
78          // If the service ID from the policy is blank, use the client ID from the token instead
79          if (serviceId.isBlank()) {
80              if (clientId != null && !clientId.isBlank()) {
81                  serviceId = clientId;
82              }
83          }
84          // Return the determined service ID
85          logger.debug("ServiceID extracted from token: "  + serviceId);
86          return serviceId;
87      }
88
89      /**
90       * Extracts the client ID from the Bearer token present in the Authorization header.
91       *
92       * @param exchange The ServerWebExchange object that contains request and response information.
93       * @return The client ID extracted from the token, or null if the token is invalid or missing.
94       */
95      private String extractClientIdFromToken(ServerWebExchange exchange) {
96          HttpHeaders headers = exchange.getRequest().getHeaders();
97          String authHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
98
99          // Check if the Authorization header exists and contains a Bearer token
100          if (authHeader != null && authHeader.startsWith(BEARER_PREFIX)) {
101              String token = authHeader.substring(BEARER_PREFIX.length());
102              return decodeClientId(token);
103          } else {
104              // Log a debug message if the Authorization header is missing or invalid
105              logger.debug("Authorization header is missing or does not contain a Bearer token");
106          }
107          return null;
108      }
109
110      /**
111       * Decodes the client ID from the JWT token.
112       *
113       * @param token The JWT token string.
114       * @return The client ID extracted from the token, or null if decoding fails.
115       */
116      private String decodeClientId(String token) {
117          try {
118              // Split the JWT token to get the payload part
119              String[] chunks = token.split("\\.");
120              Base64.Decoder decoder = Base64.getUrlDecoder();
121              String payload = new String(decoder.decode(chunks[1]));
122              JsonObject jsonObject = JsonParser.parseString(payload).getAsJsonObject();
123
124              // Return the client ID from the payload
125              return jsonObject.get("client_id").getAsString();
126          } catch (Exception e) {
127              // Log an error if decoding fails
128              logger.error("Error decoding client ID from token", e);
129              return null;
130          }
131      }
132  }