-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirebaseJWT.cs
More file actions
199 lines (160 loc) · 6.2 KB
/
FirebaseJWT.cs
File metadata and controls
199 lines (160 loc) · 6.2 KB
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
using Jose;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SpawnerWorker.SpawnerLogic
{
internal static class FirebaseJWT
{
static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
const string ProjectId = "insert your firebase project id here";
const string URL = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com";
static Dictionary<string, RSACryptoServiceProvider> cryptoServiceProviders;
static TimeSpan timeUntilRefresh;
internal static bool Verify(string token, out string userID)
{
var headers = JWT.Headers<Dictionary<string, string>>(token);
var kid = headers["kid"];
if (cryptoServiceProviders.TryGetValue(kid, out var key))
{
string unparsedPayload;
try
{
unparsedPayload = JWT.Decode(token, key, JwsAlgorithm.RS256);
}
catch (InvalidAlgorithmException)
{
userID = "INVALID ALGORITHM";
return false;
}
catch (IntegrityException)
{
userID = "INVALID TOKEN";
return false;
}
var payload = JsonConvert.DeserializeObject<TokenPayload>(unparsedPayload);
var now = ToUnixTime(DateTime.Now);
//Must be in the future
if (payload.exp <= now)
{
userID = "TOKEN_EXPIRED";
return false;
}
//Must be in the past
if (payload.auth_time >= now)
{
userID = "INVALID AUTHENTICATION TIME";
return false;
}
//Must be in the past
if (payload.iat >= now)
{
userID = "INVALID ISSUE-AT-TIME";
return false;
}
//Must correspond to projectId
if (payload.aud != ProjectId)
{
userID = "INVALID AUDIENCE";
return false;
}
if (payload.iss != "https://securetoken.google.com/" + ProjectId)
{
userID = "INVALID ISSUER";
return false;
}
userID = payload.sub;
return true;
}
userID = "INVALID TOKEN KID";
return false;
}
internal static async Task PeriodicKeyUpdate()
{
while (true)
{
var keys = await GetPublicKeysAsync();
UpdateCryptoServiceProviders(keys);
await Task.Delay(timeUntilRefresh);
}
}
static async Task<string> GetPublicKeysAsync()
{
Uri uri = new Uri(URL);
WebRequest webRequest = WebRequest.Create(uri);
using (WebResponse webResponse = await webRequest.GetResponseAsync())
{
var headers = webResponse.Headers;
var cacheControl = headers.Get("Cache-Control");
var resultString = Regex.Match(cacheControl, @"\d+").Value;
var maxAge = Int32.Parse(resultString);
timeUntilRefresh = new TimeSpan(0, 0, maxAge);
using (var stream = webResponse.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
}
}
static void UpdateCryptoServiceProviders(string json)
{
var publicKeys = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var newCryptoServiceProviders = new Dictionary<string, RSACryptoServiceProvider>();
foreach (var keyIdPEMPair in publicKeys)
{
var keyId = keyIdPEMPair.Key;
var pem = keyIdPEMPair.Value;
var certBuffer = GetBytesFromPEM(pem);
var publicKey = new X509Certificate2(certBuffer).PublicKey;
var cryptoServiceProvider = publicKey.Key as RSACryptoServiceProvider;
newCryptoServiceProviders.Add(keyId, cryptoServiceProvider);
}
cryptoServiceProviders = newCryptoServiceProviders;
}
static byte[] GetBytesFromPEM(string pem, string type = "CERTIFICATE")
{
string header = String.Format("-----BEGIN {0}-----", type);
string footer = String.Format("-----END {0}-----", type);
int start = pem.IndexOf(header) + header.Length;
int end = pem.IndexOf(footer, start);
string base64 = pem.Substring(start, (end - start));
return Convert.FromBase64String(base64);
}
static double ToUnixTime(DateTime date)
{
return (date.ToUniversalTime() - epoch).TotalSeconds;
}
}
#pragma warning disable IDE1006 // Naming Styles
class Identities
{
public List<string> email { get; set; }
}
class Firebase
{
public Identities identities { get; set; }
public string sign_in_provider { get; set; }
}
class TokenPayload
{
public string iss { get; set; }
public string aud { get; set; }
public int auth_time { get; set; }
public string user_id { get; set; }
public string sub { get; set; }
public int iat { get; set; }
public int exp { get; set; }
public string email { get; set; }
public bool email_verified { get; set; }
public Firebase firebase { get; set; }
}
#pragma warning restore IDE1006 // Naming Styles
}