2 * ========================LICENSE_START=================================
5 * Copyright (C) 2023 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oran.datafile.oauth2;
23 import java.lang.invoke.MethodHandles;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.beans.factory.annotation.Value;
33 import org.springframework.boot.context.properties.ConfigurationProperties;
34 import org.springframework.boot.context.properties.EnableConfigurationProperties;
35 import org.springframework.stereotype.Component;
37 @EnableConfigurationProperties
38 @ConfigurationProperties()
40 public class SecurityContext {
42 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
44 private long tokenTimestamp = 0;
46 private String authToken = "";
49 private static SecurityContext instance;
53 private Path authTokenFilePath;
55 public SecurityContext(@Value("${app.auth-token-file:}") String authTokenFilename) {
56 instance = this; //NOSONAR
57 if (!authTokenFilename.isEmpty()) {
58 this.authTokenFilePath = Path.of(authTokenFilename);
62 public boolean isConfigured() {
63 return authTokenFilePath != null;
66 public synchronized String getBearerAuthToken() {
67 if (!isConfigured()) {
68 logger.warn("No configuration for auth token");
72 long lastModified = authTokenFilePath.toFile().lastModified();
73 if (tokenTimestamp == 0 || lastModified != this.tokenTimestamp) {
74 this.authToken = Files.readString(authTokenFilePath);
75 this.authToken = this.authToken.trim();
76 this.tokenTimestamp = lastModified;
78 } catch (Exception e) {
79 logger.warn("Could not read auth token file: {}, reason: {}", authTokenFilePath, e.getMessage());
81 return this.authToken;