azure-identity
Loading...
Searching...
No Matches
token_cache.hpp
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
10#pragma once
11
12#include <azure/core/credentials/credentials.hpp>
13
14#include <chrono>
15#include <functional>
16#include <map>
17#include <memory>
18#include <shared_mutex>
19#include <string>
20#include <tuple>
21
22namespace Azure { namespace Identity { namespace _detail {
27 class TokenCache
28#if !defined(_azure_TESTING_BUILD)
29 final
30#endif
31 {
32#if !defined(_azure_TESTING_BUILD)
33 private:
34#else
35 protected:
36#endif
37 // A test hook that gets invoked before cache write lock gets acquired.
38 virtual void OnBeforeCacheWriteLock() const {};
39
40 // A test hook that gets invoked before item write lock gets acquired.
41 virtual void OnBeforeItemWriteLock() const {};
42
43 struct CacheKey
44 {
45 std::string Scope;
46 std::string TenantId;
47 };
48
49 struct CacheKeyComparator
50 {
51 bool operator()(CacheKey const& lhs, CacheKey const& rhs) const
52 {
53 return std::tie(lhs.Scope, lhs.TenantId) < std::tie(rhs.Scope, rhs.TenantId);
54 }
55 };
56
57 struct CacheValue
58 {
59 Core::Credentials::AccessToken AccessToken;
60 std::shared_timed_mutex ElementMutex;
61 };
62
63 mutable std::map<CacheKey, std::shared_ptr<CacheValue>, CacheKeyComparator> m_cache;
64 mutable std::shared_timed_mutex m_cacheMutex;
65
66 private:
67 TokenCache(TokenCache const&) = delete;
68 TokenCache& operator=(TokenCache const&) = delete;
69
70 // Checks cache element if cached value should be reused. Caller should be holding ElementMutex.
71 static bool IsFresh(
72 std::shared_ptr<CacheValue> const& item,
73 DateTime::duration minimumExpiration,
74 std::chrono::system_clock::time_point now);
75
76 // Gets item from cache, or creates it, puts into cache, and returns.
77 std::shared_ptr<CacheValue> GetOrCreateValue(
78 CacheKey const& key,
79 DateTime::duration minimumExpiration) const;
80
81 public:
82 TokenCache() = default;
83 ~TokenCache() = default;
84
98 Core::Credentials::AccessToken GetToken(
99 std::string const& scopeString,
100 std::string const& tenantId,
101 DateTime::duration minimumExpiration,
102 std::function<Core::Credentials::AccessToken()> const& getNewToken) const;
103 };
104}}} // namespace Azure::Identity::_detail