-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
AuthenticationRecord.cs
223 lines (189 loc) · 9.77 KB
/
AuthenticationRecord.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Microsoft.Identity.Client;
namespace Azure.Identity
{
/// <summary>
/// Account information relating to an authentication request.
/// </summary>
/// <seealso cref="TokenCachePersistenceOptions"/>.
public class AuthenticationRecord
{
internal const string CurrentVersion = "1.0";
private const string UsernamePropertyName = "username";
private const string AuthorityPropertyName = "authority";
private const string HomeAccountIdPropertyName = "homeAccountId";
private const string TenantIdPropertyName = "tenantId";
private const string ClientIdPropertyName = "clientId";
private const string VersionPropertyName = "version";
private static readonly JsonEncodedText s_usernamePropertyNameBytes = JsonEncodedText.Encode(UsernamePropertyName);
private static readonly JsonEncodedText s_authorityPropertyNameBytes = JsonEncodedText.Encode(AuthorityPropertyName);
private static readonly JsonEncodedText s_homeAccountIdPropertyNameBytes = JsonEncodedText.Encode(HomeAccountIdPropertyName);
private static readonly JsonEncodedText s_tenantIdPropertyNameBytes = JsonEncodedText.Encode(TenantIdPropertyName);
private static readonly JsonEncodedText s_clientIdPropertyNameBytes = JsonEncodedText.Encode(ClientIdPropertyName);
private static readonly JsonEncodedText s_versionPropertyNameBytes = JsonEncodedText.Encode(VersionPropertyName);
internal AuthenticationRecord()
{
}
internal AuthenticationRecord(AuthenticationResult authResult, string clientId)
{
Username = authResult.Account.Username;
Authority = authResult.Account.Environment;
AccountId = authResult.Account.HomeAccountId;
TenantId = authResult.TenantId;
ClientId = clientId;
}
internal AuthenticationRecord(string username, string authority, string homeAccountId, string tenantId, string clientId)
{
Username = username;
Authority = authority;
AccountId = BuildAccountIdFromString(homeAccountId);
TenantId = tenantId;
ClientId = clientId;
}
/// <summary>
/// The user principal or service principal name of the account.
/// </summary>
public string Username { get; private set; }
/// <summary>
/// The authority host used to authenticate the account.
/// </summary>
public string Authority { get; private set; }
/// <summary>
/// A unique identifier of the account.
/// </summary>
public string HomeAccountId { get => AccountId.Identifier; }
/// <summary>
/// The tenant the account should authenticate in.
/// </summary>
public string TenantId { get; private set; }
/// <summary>
/// The client id of the application which performed the original authentication
/// </summary>
public string ClientId { get; private set; }
internal AccountId AccountId { get; private set; }
internal string Version { get; private set; } = CurrentVersion;
/// <summary>
/// Serializes the <see cref="AuthenticationRecord"/> to the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> which the serialized <see cref="AuthenticationRecord"/> will be written to.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public void Serialize(Stream stream, CancellationToken cancellationToken = default)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
SerializeAsync(stream, false, cancellationToken).EnsureCompleted();
}
/// <summary>
/// Serializes the <see cref="AuthenticationRecord"/> to the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to which the serialized <see cref="AuthenticationRecord"/> will be written.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public async Task SerializeAsync(Stream stream, CancellationToken cancellationToken = default)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
await SerializeAsync(stream, true, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deserializes the <see cref="AuthenticationRecord"/> from the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> from which the serialized <see cref="AuthenticationRecord"/> will be read.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public static AuthenticationRecord Deserialize(Stream stream, CancellationToken cancellationToken = default)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
return DeserializeAsync(stream, false, cancellationToken).EnsureCompleted();
}
/// <summary>
/// Deserializes the <see cref="AuthenticationRecord"/> from the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> from which the serialized <see cref="AuthenticationRecord"/> will be read.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
public static async Task<AuthenticationRecord> DeserializeAsync(Stream stream, CancellationToken cancellationToken = default)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
return await DeserializeAsync(stream, true, cancellationToken).ConfigureAwait(false);
}
private async Task SerializeAsync(Stream stream, bool async, CancellationToken cancellationToken)
{
using (var json = new Utf8JsonWriter(stream))
{
json.WriteStartObject();
json.WriteString(s_usernamePropertyNameBytes, Username);
json.WriteString(s_authorityPropertyNameBytes, Authority);
json.WriteString(s_homeAccountIdPropertyNameBytes, HomeAccountId);
json.WriteString(s_tenantIdPropertyNameBytes, TenantId);
json.WriteString(s_clientIdPropertyNameBytes, ClientId);
json.WriteString(s_versionPropertyNameBytes, Version);
json.WriteEndObject();
if (async)
{
await json.FlushAsync(cancellationToken).ConfigureAwait(false);
}
else
{
json.Flush();
}
}
}
private static async Task<AuthenticationRecord> DeserializeAsync(Stream stream, bool async, CancellationToken cancellationToken)
{
var authProfile = new AuthenticationRecord();
using JsonDocument doc = async ? await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false) : JsonDocument.Parse(stream);
foreach (JsonProperty prop in doc.RootElement.EnumerateObject())
{
switch (prop.Name)
{
case UsernamePropertyName:
authProfile.Username = prop.Value.GetString();
break;
case AuthorityPropertyName:
authProfile.Authority = prop.Value.GetString();
break;
case HomeAccountIdPropertyName:
authProfile.AccountId = BuildAccountIdFromString(prop.Value.GetString());
break;
case TenantIdPropertyName:
authProfile.TenantId = prop.Value.GetString();
break;
case ClientIdPropertyName:
authProfile.ClientId = prop.Value.GetString();
break;
case VersionPropertyName:
authProfile.Version = prop.Value.GetString();
if (authProfile.Version != CurrentVersion)
{
throw new InvalidOperationException($"Attempted to deserialize an {nameof(AuthenticationRecord)} with a version that is not the current version. Expected: '{CurrentVersion}', Actual: '{authProfile.Version}'");
}
break;
}
}
return authProfile;
}
private static AccountId BuildAccountIdFromString(string homeAccountId)
{
//For the Microsoft identity platform (formerly named Azure AD v2.0), the identifier is the concatenation of
// Microsoft.Identity.Client.AccountId.ObjectId and Microsoft.Identity.Client.AccountId.TenantId separated by a dot.
var homeAccountSegments = homeAccountId.Split('.');
AccountId accountId;
if (homeAccountSegments.Length == 2)
{
accountId = new AccountId(homeAccountId, homeAccountSegments[0], homeAccountSegments[1]);
}
else
{
accountId = new AccountId(homeAccountId);
}
return accountId;
}
}
}