-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
TokenHelper.cs
76 lines (68 loc) · 2.56 KB
/
TokenHelper.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text.Json;
using Azure.Core;
namespace Azure.Identity
{
internal static class TokenHelper
{
public static (string ClientId, string TenantId, string Upn, string ObjectId) ParseAccountInfoFromToken(string token)
{
Argument.AssertNotNullOrEmpty(token, nameof(token));
var parts = token.Split('.');
if (parts.Length != 3)
{
throw new ArgumentException("Invalid token", nameof(token));
}
(string ClientId, string TenantId, string Upn, string ObjectId) result = default;
try
{
string convertedToken = parts[1].Replace('_', '/').Replace('-', '+');
switch (parts[1].Length % 4)
{
case 2:
convertedToken += "==";
break;
case 3:
convertedToken += "=";
break;
}
Utf8JsonReader reader = new Utf8JsonReader(Convert.FromBase64String(convertedToken));
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.PropertyName)
{
switch (reader.GetString())
{
case "appid":
reader.Read();
result.ClientId = reader.GetString();
break;
case "tid":
reader.Read();
result.TenantId = reader.GetString();
break;
case "upn":
reader.Read();
result.Upn = reader.GetString();
break;
case "oid":
reader.Read();
result.ObjectId = reader.GetString();
break;
default:
reader.Read();
break;
}
}
}
}
catch
{
AzureIdentityEventSource.Singleton.UnableToParseAccountDetailsFromToken();
}
return result;
}
}
}