View Javadoc
1   /*
2    * Copyright 2019 the original author or authors.
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
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
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   */
16  
17  package org.bremersee.security.authentication;
18  
19  import java.nio.charset.StandardCharsets;
20  import java.security.MessageDigest;
21  import java.security.NoSuchAlgorithmException;
22  import java.util.Base64;
23  import java.util.Optional;
24  import org.bremersee.exception.ServiceException;
25  import org.springframework.util.MultiValueMap;
26  
27  /**
28   * The access token retriever properties.
29   *
30   * @author Christian Bremer
31   */
32  public interface AccessTokenRetrieverProperties {
33  
34    /**
35     * Gets token endpoint.
36     *
37     * @return the token endpoint
38     */
39    String getTokenEndpoint();
40  
41    /**
42     * Gets basic auth properties.
43     *
44     * @return the basic auth properties or {@link Optional#empty()}, if no basic auth is required
45     */
46    default Optional<BasicAuthProperties> getBasicAuthProperties() {
47      return Optional.empty();
48    }
49  
50    /**
51     * Create cache key.
52     *
53     * @return the cache key
54     */
55    String createCacheKey();
56  
57    /**
58     * Create an hashed cache key.
59     *
60     * @return the hashed cache key
61     */
62    default String createCacheKeyHashed() {
63      final String cacheKey = createCacheKey();
64      return Optional.ofNullable(cacheKey)
65          .map(key -> {
66            try {
67              MessageDigest md = MessageDigest.getInstance("SHA-256");
68              byte[] hashBytes = md.digest(key.getBytes(StandardCharsets.UTF_8));
69              return Base64.getEncoder().encodeToString(hashBytes);
70            } catch (NoSuchAlgorithmException e) {
71              throw ServiceException.internalServerError("Creating hash failed.", e);
72            }
73          })
74          .orElse(cacheKey);
75    }
76  
77    /**
78     * Create http request body.
79     *
80     * @return the multi value map
81     */
82    MultiValueMap<String, String> createBody();
83  
84  }